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