I’ve been trying to get the number of a range's loop but I cant make it work It might be something pretty obvious which I’m missing, but I can’t figure it out so I’m asking for help.
My data/foo/ folder has a few yml files each of which has a structure like this:
name: "Foo"
items:
-
bar: "barfoo"
-
bar: "foobar"
{{ range $i, .Site.Data.foo }}
<li{{ if (eq $i 0) }} class="active"{{ end }}>
<a href="#{{ .name | urlize | lower }}">{{ .name | markdownify }}</a>
</li>
{{ end }}
$i is not an int; it contains the whole map.
I need to get the first and last item in the loop. There must be some way, but I can’t make it work out of the box.
OK, I see. So, foo is a map, and the range will give you the key/value pairs.
If you do:
{{ range $i, $e .Site.Data.foo.items }}
{{ end }}
It is hard for me to tell how your YAML look like, but my main point above should be correct. Not that maps have no defined order, but you could add a counter yourself via .Scratch.
So what I mean is that if I do 2 ranges, then the index is a number. But I need to get the number of the first range’s items.
{{ range $i, $e:= .Site.Data.foo }}
{{ range $k, $el:= $e.items }}
{{ $i }} <!-- $i is a map instead of a number -->
{{ $k }} <!-- $k is the index number of $el indeed -->
{{ end }}
{{ end }}