A bird in the hand is worth two in the bush
Context Aware Template Function package main import ( "html/template" "os" ) const hometmpl = ` {{define "home"}} <html> <body> *Welcome* <a href="/flowers">Go to the Flowers gallery</a> <a href="/puppies">Go to the Puppies gallery</a> {{if isAdmin}} <a href="/admin/nuke">Go to the big red nuclear button</a> {{end}} </body> </html> {{end}} ` var t *template.Template var defaultfuncs = map[string]interface{}{ "isAdmin": func() bool { return false }, } func init() { t = template.New("home").Funcs(defaultfuncs) t, _ = t.Parse(hometmpl) } func main() { token := "0xCAFEBABE" // Or extracted from the http.Request t.Funcs(template.FuncMap{"isAdmin": func() bool { return token == "0xCAFEBABE" }}) t.ExecuteTemplate(os.Stdout, "home", nil) }
Context Aware Template Function
package main import ( "html/template" "os" ) const hometmpl = ` {{define "home"}} <html> <body> *Welcome* <a href="/flowers">Go to the Flowers gallery</a> <a href="/puppies">Go to the Puppies gallery</a> {{if isAdmin}} <a href="/admin/nuke">Go to the big red nuclear button</a> {{end}} </body> </html> {{end}} ` var t *template.Template var defaultfuncs = map[string]interface{}{ "isAdmin": func() bool { return false }, } func init() { t = template.New("home").Funcs(defaultfuncs) t, _ = t.Parse(hometmpl) } func main() { token := "0xCAFEBABE" // Or extracted from the http.Request t.Funcs(template.FuncMap{"isAdmin": func() bool { return token == "0xCAFEBABE" }}) t.ExecuteTemplate(os.Stdout, "home", nil) }