Search code examples
gohugogo-templates

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 ?


Solution

  • 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}}{{.}}
     {{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.