英文:
Go template and function
问题
在我的 Go 代码中,我经常这样使用 if
:
if user && user.Registered { }
在 Go 模板中,等效的代码是:
{{ if and .User .User.Registered }} {{ end }}
不幸的是,如果 .User
是 nil
,模板中的代码会失败。:/
在 Go 模板中是否有可能实现相同的功能呢?
英文:
In my go code I often use if
like this
if user && user.Registered { }
equivalent code in go templates would be
{{ if and .User .User.Registered }} {{ end }}
Unfortunately code in the template fails, if .User
is nil
:/
Is it possible to achieve the same thing in go templates?
答案1
得分: 12
模板中的and
函数不像Go语言的&&
运算符那样进行短路评估。
在调用函数之前,and
函数的参数会被求值。即使.User
为nil,表达式.User.Registered
也会被求值。
修复方法是使用嵌套的if
:
{{if .User}}{{if .User.Registered}} {{end}}{{end}}
你可以通过使用模板函数来避免嵌套的if
或with
:
func isRegistered(u *user) bool {
return u != nil && u.Registered
}
const tmpl = `{{if isRegistered .User}}registered{{else}}not registered{{end}}`
t := template.Must(template.New("").Funcs(template.FuncMap{"isRegistered": isRegistered}).Parse(tmpl))
英文:
The template and
function does not do short circuit evaluation like the Go &&
operator.
The arguments to the and
function are evaluated before the function is called. The expression .User.Registered
is always evaluated, even if .User
is nil.
The fix is to use nested if
:
{{if .User}}{{if .User.Registered}} {{end}}{{end}}
You can avoid the nested if
or with
by using a template function:
func isRegistered(u *user) bool {
return u != nil && u.Registered
}
const tmpl = `{{if isRegistered .User}}registered{{else}}not registered{{end}}`
t := template.Must(template.New("").Funcs(template.FuncMap{"isRegistered": isRegistered}).Parse(tmpl))
答案2
得分: 3
另一种选择是使用{{with}}
操作而不是and
模板函数。
引用自text/template
包的文档:
> {{with pipeline}} T1 {{end}}
如果管道的值为空,则不生成输出;
否则,dot被设置为管道的值,并执行T1。
使用{{with}}
通常会导致更清晰和更简短的代码,因为在{{with}}
内部,点.
已经设置为非空的"wrapper",在我们的例子中是.User
;此外,您不必担心and
模板函数的参数如何以及是否被评估。
重写您的模板:
{{with .User -}}
{{if .Registered}}REGISTERED{{end}}
{{- end}}
在没有用户和有用户的情况下进行测试:
t := template.Must(template.New("").Parse(tmpl))
fmt.Println("No user:")
if err := t.Execute(os.Stdout, nil); err != nil {
panic(err)
}
u := struct{ Registered bool }{true}
fmt.Printf("User: %+v\n", u)
if err := t.Execute(os.Stdout, map[string]interface{}{"User": u}); err != nil {
panic(err)
}
输出结果(在Go Playground上尝试):
No user:
User: {Registered:true}
REGISTERED
英文:
Another option is to use the {{with}}
action instead of the and
template function.
Quoting from package doc of text/template
:
> {{with pipeline}} T1 {{end}}
If the value of the pipeline is empty, no output is generated;
otherwise, dot is set to the value of the pipeline and T1 is
executed.
Using {{with}}
often results in cleaner and shorter code, as inside the {{with}}
the dot .
is already set to the non-empty "wrapper", the .User
in our case; moreover you don't have to worry about how and if the arguments of the and
template function are evaluated.
Your template rewritten:
{{with .User -}}
{{if .Registered}}REGISTERED{{end}}
{{- end}}
Testing it without and with a user:
t := template.Must(template.New("").Parse(tmpl))
fmt.Println("No user:")
if err := t.Execute(os.Stdout, nil); err != nil {
panic(err)
}
u := struct{ Registered bool }{true}
fmt.Printf("User: %+v\n", u)
if err := t.Execute(os.Stdout, map[string]interface{}{"User": u}); err != nil {
panic(err)
}
Output (try it on the Go Playground):
No user:
User: {Registered:true}
REGISTERED
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论