{{ 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 ?
CodePudding user response:
Hugo has Math functions
First find reminder than check it in a if clause
Modulus of two integers can be find with mod $number 2
{{- $reminder := mod $key 2 }}
{{ if eq $reminder 0 }}
<p >{{- $value.name -}}</p>
{{ else }}
<p>{{- $value.name -}}</p>
{{ end }}
CodePudding user response:
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.