How counting up a variable in range

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)?

No. This is a limitation with Go templates.

But there is a suggested solution to this here:

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.

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.

1 Like

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.

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

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:

1 Like

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

Terrific!!! Thanks I’m using it now

Just a small fix, you can use Add method directly.

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

This thread is really old, Go has changed, and you don’t need to initialize a Scratch to count.

{{ $i := 0 }}
{{ range $foo }}
  {{ $i = add $i 1 }}
{{ end }}

{{ $globalPopulation := 0 }}
{{ range $nations }}
  {{ $globalPopulation = add $globalPopulation .population }}
{{ end }}