Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go template and function

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?

like image 391
Goranek Avatar asked Feb 13 '17 16:02

Goranek


Video Answer


1 Answers

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

like image 191
Bayta Darell Avatar answered Sep 20 '22 02:09

Bayta Darell