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 .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))
playground example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With