How to filter even and odd elements?


{{ if eq ($key % 2) 0 }} gives: unexpected "%" in operand

{{ if $key % 2 == 0 }} gives: unexpected "%" in operand

So how do I find even and odd keys ?


Toggle a boolean variable to detect odd and even elements in a range.

 {{- $odd := false}}
 {{range .}}
    {{$odd = not $odd}}
    {{if $odd}}odd:  {{else}}even: {{end}}{{.}}

Run an example on the playground.

The first iteration is considered to be odd. Initialize with $odd := true to make the first iteration even.

This approach works with Go templates in any context (not just Hugo). This approach also works when ranging over a map.

Answered By – Bayta Darell

Answer Checked By – David Goodson (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.