Using if statements inside templates really puzzles me.
I am trying to put class = "active" inside a navigation list created using golang templates to make the main menu of a tab that detects an active tab. Here is my attempt:
{{define "header"}} <!DOCTYPE html> <html> <head> <title>Geoprod</title> {{template "stylesheet" .}} </head> <body> <nav class="navbar" role="navigation"> <div class="navbar-header"> <a{{if eq .Active "accueil"}} class="active"{{end}} href="/">Geoprod</a> </div> <div class="navbar-body"> <ul class="navbar-list"> <li{{if eq .Active "societe"}} class="active"{{end}}><a href="/societe">Société</a></li> <li{{if eq .Active "dossier"}} class="active"{{end}}><a href="/dossier">Dossier</a></li> <li{{if eq .Active "temps"}} class="active"{{end}}><a href="/temps">Temps</a></li> <li{{if eq .Active "mails"}} class="active"{{end}}><a href="/mails">Mails</a></li> </ul> </div> </nav> {{end}}
And in main.go:
var FuncMap = template.FuncMap{ "eq": func(a, b interface{}) bool { return a == b }, } var templates = template.Must(template.ParseGlob("templates/*.html"))
and in func main ()
templates.Funcs(FuncMap)
The program compiles, but I found out that adding {{if eq .Active "something"}} class="active"{{end}} (^^, which I included here) causes the program to no longer display text. Any idea why?
go if-statement go-templates
Nicolas marshall
source share