Detect every odd post in a range

#1

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

#2

Untested, but should work:

{{ range $i,$p := where .Data.Pages "Section" "services" }}
  {{if not (modBool $i 2)}}
     it's odd
   {{end}}
 {{end}}
1 Like
[SOLVED] Alternate display on odd and even with range
#3

Works perfect, thanks!

#4

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}}
#5

Surely it should be:

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

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

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

#7

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

#8

why should i declare $p variable?

#9

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