Using conditions inside templates

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&eacutet&eacute</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?

+7
go if-statement go-templates
source share
1 answer

I tried converting your code into a minimal working example, and I believe your code and template work as expected. You can see my code (and run it) on Go Playground .

My guess is that what went wrong: did you notice that {{define ...}} defines only a template for future use. You still need to tell Go to use this template, either using {{ template "header" }} , or similar in the main template, or using templates.ExecuteTemplate .

+3
source share

All Articles