去模板和功能 [英] Go template and function
问题描述
在我的代码中,我经常使用如果
像这样
如果用户&& user.Registered {}
go模板中的等效代码将是
{{if and .User .User.Registered}} {{end}}
不幸的是,如果 .User
是 nil
,那么模板中的代码将失败。 / b>
是否有可能在go模板中实现同样的功能?
模板和
函数不会执行短路评估,例如Go &&
运算符。
code>和函数在函数被调用之前被求值。即使 .User
为零,表达式 .User.Registered
也总是被计算。
如果使用嵌套:
{{if .User}} {{if .UserRegistered}} {{end}} {{end}}
通过使用a可以避免嵌套 if
或与
模板函数:
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))
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?
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 .UserRegistered}} {{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))
这篇关于去模板和功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!