Access range's count

Hello.

I’ve been trying to get the number of a range's loop but I cant make it work :confused: 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.

Thanks in advance!

Try

{{ range $i, $e := .Site.Data.foo }}

Thanks for the reply!

I had already tried that, just in case, but it doesn’t make any difference if I declare a variable in the range or not regarding the count.

It’s just that if I declare the var then $i returns the name otherwise it contains the whole yml's file contents.

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.

I’m using that a little later because I need to loop through the items and there $i is indeed an int.

But how can I get an index count without custom Scratch variables in the above case? To visualize my structure:

data/foo/foo.yml
data/foo/bar.yml
...

And each yml's contents are:

name: "Foo"
items:
-
    bar: "barfoo"
-
    bar: "foobar"

So basically when I do {{ range $i, $vars := .Site.Data.foo }} I want $i to be a number instead of a map (basically the number of yml files).

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

I made it to work by

  1. moving the data to a single data file
  2. switching to toml

Now, I’m pretty sure there’s a bug somewhere because the yaml syntax is fine.