Detect every odd post in a range

I have a simple range :

{{ range where .Data.Pages "Section" "services" }}
{{end}}

I want to detect everytime the range loop hits a odd number.

Post1 = odd
Post2 = event
Post3 = odd

{{ range where .Data.Pages "Section" "services" }}
  {{if odd}}
     it's odd
   {{end}}
 {{end}}

How do I achieve this?

Thanks

Untested, but should work:

{{ range $i,$p := where .Data.Pages "Section" "services" }}
  {{if not (modBool $i 2)}}
     it's odd
   {{end}}
 {{end}}
5 Likes

Works perfect, thanks!

I’m using this snippet on a site currently, but I have an issue. It prints every item in the range twice.

{{ range $i,$p := where .Data.Pages "Section" "services" }}
Even content
  {{if not (modBool $i 2)}}
Odd content
   {{end}}
 {{end}}

Surely it should be:

{{ range $i,$p := where .Data.Pages "Section" "services" }}

  {{if not (modBool $i 2)}}
Odd content
  {{else}}
Even content
  {{end}}
{{end}}

Agree with @Jonathan_Griffin. Your “Odd content” piece is outside your {{ if }} so, it won’t be subject to the modBool filtering.

Wow, I feel stupid now. But that was it. I interpreted the snippet the wrong way.

why should i declare $p variable?

If you only have one variable returned (e.g. if you only had $i), it will contain the value of the array element. If you specify two variables (e.g $i, $p) the first variable will hold the index of the array element and the second holds the value. So even if you only want the index, you still need to declare $p.

1 Like