Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go: Is there a modulus I can use inside a template

Tags:

go

My question is as stated in the title. I am trying to do something like:

{{range $index, $element := .Products}}
    {{if $index % 4 == 0}}<div class="row">{{end}}
        <div class="columns small-3 product">
            <img src="/img/{{.ImageUrl}}" alt="{{.ImageUrl}}" />
                <a href="/product">
                    <h3>{{.Title}}</h3>
                </a>
                <p>
                  {{.Description}}
                </p>
                <p>
                    {{.Price}} / liter
                </p>
                </div>
        {{if index % 4 == 0}}</div>{{end}}
{{end}}

I get the error:

template: products.html:9: unexpected "%" in operand

Is there an alternate way to do modulus in a template?

like image 440
Nick Rucci Avatar asked Apr 02 '16 04:04

Nick Rucci


1 Answers

Add a template function with the logic you need. For example:

t := template.New("")
t.Funcs(template.FuncMap{"mod": func(i, j int) bool { return i%j == 0 }})
t.Parse(`... {{if mod $index 4}}<div class="row">{{{end}} ...`)

playground example

like image 100
Bayta Darell Avatar answered Sep 23 '22 13:09

Bayta Darell