Search code examples
gogo-templates

How to do IF/ELSE conditions inside LOOP in golang templates?


I tried to do this test to figure out how to make conditions like this:

<h1>Country Index</h1>

<style>
.odd{
    background: orange;
    color: black;
    font-size: 1.5em;
}
.even{
    background: rgb(0, 121, 235);
    color: white;
    font-size: 1.5em;
}
</style>

<ul>
    {{ range $index, $item := .Tee }}
        {{ if $index % 2 == 0 }}
            <li class="even">{{ $index }} - {{ $item }}</li>
        {{ else }}
            <li class="odd">{{ $index }} - {{ $item }}</li>
        {{ end }}
    {{ end }}
</ul>

I got this error "unexpected "%" in operand".

Any suggestions to solve this?


Solution

  • You can't use operators like +, -, *, /, or % in templates, unfortunately. Instead you have to write custom functions and use a funcMap to bring them into your template.

    Here's an example on the Go Playground that detects even integers applied to a slightly modified version of your template text.

    https://play.golang.org/p/LWEhE_TI31o