How to get first item of Yaml list

I have the following .md file:

limits_section:
  title: Foo bar
  tabs:
    - title: Foo bar
      foo: bar
    - title Bar foo
      foo: bar

I can successfully iterate through it with {{ range .Params.limits_section.tabs }}

However, I am facing difficulties fetching the first element of the list.
To get the first element I tried:
{{ $firstTab := index .Params.limits_section.tabs 0 }}
but I get the error:
error calling index: index of untyped nil

The following suggested solutions don’t solve this issue:

When I print the contents of .Params.limits_section.tabs I get [map[...] map[...]] and based on the godocs:

Each indexed item must be a map, slice, or array.

So, I don’t understand why this doesn’t work.
Thanks for the support!

You may have content that does not have that front matter param set, so for those cases you are calling index on nil. Try it inside a with (or test if isset):

{{ with .Params.limits_section.tabs }}
  {{ $firstTab := index . 0 }}
  {{ $firstTab }}
{{ end }}

What does that mean exactly? My content is an array, as seen in the output of .Params.limits_section.tabs.

I tried your snippet and it works, but then I cannot reference the $firstTab variable outside of the with block. I would have to use Scratch or something to accomplish that.

For a simple operation as fetching the first element of an array, I find this process quite cumbersome…

In other words, there is really no single line statement that will assign the first item of the array to a variable?

By ‘content’ I meant your content files, i.e. your .md files.

I am assuming here that you put this chunk

limits_section: 
  title: Foo bar 
  tabs: 
    - title: Foo bar 
      foo: bar 
    - title: Bar foo 
    - foo: bar

into the front matter (Front matter | Hugo) of your content / .md file.

The error may occur when not all .md files have that front matter parameter included. For example if one file does not have limits_section defined, or has it but not tabs.

2 Likes

You were right. I had 2 more markdown files using the same template, but the specific content was missing. Thanks!