Using conditions inside templates

Nicolas Marshall picture Nicolas Marshall · Jul 15, 2014 · Viewed 17.8k times · Source

The use of if statements inside templates really is puzzling me.

I'm trying to put a class = "active" inside a nav list made with golang templates, to do a basic tab menu that detects the active tab. Here's 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've found out adding the {{if eq .Active "something"}} class="active"{{end}} (^^ which I included here) causes the program to not display any text anymore. Any idea why?

Answer

jochen picture jochen · May 11, 2015

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

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