How counting up a variable in range


#1

Sometimes you need a simple counter… for example unique

id="myid{{ $count }}"

I thought about (simplified):

{{ $count := 1 }}
...
{{ range $value.Pages }} 
    {{ $count := add $count 1 }}
         <div id="myuid{{ $count }}">...</div>
{{ end }}

but everything i tried like in other languages failed or gives me always back the number 2
Is there a solution in hugo (0.12)?


#2

No. This is a limitation with Go templates.

But there is a suggested solution to this here:


#3

ok, thats cracy. That means for me (and others), that i have to write a script, which generates a uniq_id and write that in the coresponding front matter.


#4

OK, I did not look too hard on your question. Your construction with the counter variable doesn’t work.

But you can achieve similar by adding the index variable to your range construct.

{{ range $index, $element := $value.Pages }}

EDIT IN: This will start at 0, but you can use “add” to add 1.


#5

for hugo 0.12 this one worked fine:

{{ range $index, $page :=  $value.Pages }}
{{ $c :=add $index 1 }}
{{ $c }}= value of $c... 
    {{ if eq ( mod $c 4 ) 1 }}
         {{ $c }} first one of each 4... ($c=1,5,...)
    {{ end }}
{{ end }}

$index counts up as expected, {{ $c }} prints out the value of c, but the if-clause is in 0.13 broken.


#6

Reported and fixed in https://github.com/spf13/hugo/issues/961


#7

after reading the reported issue and the coresponding discussion, maybe someone find my temporary workaround useful: don’t mix up fixed/raw numbers with calculated ones. Use only calculated…

instead of

{{ if eq ( mod $c 4 ) 1 }}

use:

{{ if eq ( mod $c 4 ) (add 1 0) }}

but {{ add 0 0 }} is not working for 0, use {{ sub 1 1 }} …

this works for me :wink:


#8

I found another method without depending on the index var which might be at times a string when having a dictionary, and also with being able to sort array…

  {{ $.Scratch.Set "counter" 0 }}
  {{range sort .Params.employees}}
    {{ $.Scratch.Set "counter" (add ($.Scratch.Get "counter") 1) }}
    I am the number {{$.Scratch.Get "counter"}} in loop!
  {{end}}