Search code examples
cssgogo-html-template

css class based on loaded template


I've got this bootstrap nav in my _base.html template like this:

<ul class="nav navbar-nav">
   <li><a href="/" class="">Home</a></li>
   <li><a href="/blog/">Blog</a></li>
</ul>

Using Golang I want to add a

class="active"

to the corresponding list-item.

I've read the html/template docs and articles like thisone, but it appears to me that I have to write a golang function that adds

class="active"

to every correspondending corresponding list-item. But somehow still I think it would be cleaner if I could just add something like

<ul>
    <li{{ if .template = "index.html" }} class="active"{{ end }}><a href="/">Home</a></li>
    <li{{ if .template = "blog.html" }} class="active"{{ end }}><a href="/blog/">Blog</a></li>
</ul>

or something like that. I remember Rob Pike saying Golang should be doing all the calculations for you, but why is there an "if" statement in the html/template-package?


Solution

  • I personally often implement a small eq helper for tasks like that:

    var tmpl = template.Must(template.New("").Funcs(template.FuncMap{
        "eq": func(a, b interface{}) bool {
            return a == b
        },
    }).ParseGlob("templates/*.html")
    

    Example Usage:

    <li{{if eq .Active "index"}} class="active"{{end}}><a href="/">Home</a></li>
    

    But use it only for the display logic itself. It's a good practice to keep the display logic and the real computation apart.