Adding a counter to Range

I am looping through a file with Range, and want to create IDs for each of my divs with incrementing numbers. I am unable to get a counter to work, my code is below:

{{ if .Params.grid }}
  {{ $counter := 0 }}
  {{ range .Params.grid }}

  {{ add $counter 1 }}

  <div class="grid-person w-full md:w-1/2 lg:w-1/3" id="{{ $counter }}"> {{ .info }}</div>

   {{ end }}
{{ end }}

I have multiple divs showing up but each ID still shows up as the number 1, what am I doing wrong? I was hoping that each time it loops through this set of info it would increment the counter value.

1 Like

You’ve got two things wrong:

  • you’re declaring your counter inside the range, but it needs to be declared outside the range
  • when you increment the counter, you’re not re-assigning the value to the counter

Try this instead:

{{ if .Params.grid }}
  {{ $counter := 0 }}
  {{ range .Params.grid }}
    {{ $counter = add $counter 1 }}
    <div class="grid-person w-full md:w-1/2 lg:w-1/3" id="{{ $counter }}"> {{ .info }}</div>
  {{ end }}
{{ end }}
3 Likes

Ah! Makes sense as to why they were showing up the same, as it was declared in the wrong place.

Note also that $counter = add $counter 1 is not a typo. Reasonably one would think := is correct, but apparently this redeclares the variable while = re-assigns it.

Just mentioning for the 1k+ people who have seen this post, some who may be struggling like me with a simple counter increment.