英文:
Golang template ignore if no match
问题
我正在尝试转换一个 golang 模板,并允许在找不到匹配项时忽略。这可能吗?
package main
import (
"bytes"
"fmt"
"text/template"
)
type Person struct {
Name string
Age int
}
type Info struct {
Name string
Id int
}
func main() {
msg := "Hello {{ .Id }} With name {{ .Name }}"
p := Person{Name: "John", Age: 24}
i := Info{Name: "none", Id: 5}
t := template.New("My template")
t, _ = t.Parse(msg)
buf := new(bytes.Buffer)
t.Execute(buf, p)
fmt.Println(buf.String())
buf = new(bytes.Buffer)
t.Execute(buf, i)
fmt.Println(buf.String())
}
我希望输出结果为:
Hello {{ .Id }} with name John
Hello 5 With name none
英文:
I am trying to convert a golang template, and allow ignoring if the match is not found. Is that possible?
package main
import (
"bytes"
"fmt"
"text/template"
)
type Person struct {
Name string
Age int
}
type Info struct {
Name string
Id int
}
func main() {
msg := "Hello {{ .Id }} With name {{ .Name }}"
p := Person{Name: "John", Age: 24}
i := Info{Name: "none", Id: 5}
t := template.New("My template")
t, _ = t.Parse(msg)
buf := new(bytes.Buffer)
t.Execute(buf, p)
fmt.Println(buf.String())
buf = new(bytes.Buffer)
t.Execute(buf, i)
fmt.Println(buf.String())
}
I would like this to print
Hello {{ .Id }} with name John
Hello 5 With name none
答案1
得分: 1
如果你希望只在名称不为空字符串时打印名称:
"Hello {{ .Id }} With name {{ if .Name }}{{ .Name }}{{ end }}"
否则,如果你希望打印其他内容:
"Hello {{ .Id }} With name {{ if .Name }}{{ .Name }}{{ else }}none!{{ end }}"
Playground - 还可以查看html/template和text/template的比较运算符。
英文:
If you want it to print name only when it's not an empty string:
"Hello {{ .Id }} With name {{ if .Name }}{{ .Name }}{{ end }}"
Else, if you want to it print something else:
"Hello {{ .Id }} With name {{ if .Name }}{{ .Name }}{{ else }}none!{{ end }}"
Playground - also see the comparison operators for html/template and text/template.
答案2
得分: 0
一个模板可以包含if语句,允许你执行你所需的操作。以下示例允许在提供了列表时显示列表,否则显示一条消息。
{{if .MyList}}
{{range .MyList}}
{{.}}
{{end}}
{{else}}
没有提供列表。
{{end}}
使用这种方法,我认为你可以实现你的需求。但是,由于你想保留未处理的{{.Id}}
,可能不太美观。
英文:
A template can contain if statements which allow you to do what you would need. The following example allows displaying a list if supplied, or when not supplied putting a message.
{{if .MyList}}
{{range .MyList}}
{{.}}
{{end}}
{{else}}
There is no list provided.
{{end}}
Using this approach I think you can achieve what you need. But it might not be pretty as you want to leave the unprocessed {{.Id}}
in place.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论