Accessing the first item in a .Params.categories array

For some reason, the solution in this other topic isn’t working for me. I’m not sure how my setup is different, but I can’t seem to get it to work.

The code I have in list.html is:

    {{ range .Pages }}
    <div id="{{ .Params.categories }}">
        <p><strong><a href="{{ .Permalink }}">{{ .Title }}</a></strong></p>
        <p>{{ .Page.Description }}</p>
    </div>
    {{ end }}

With this code, the first div converts to:

<div id="[category]">

That specific page has just one category, but .Params.categories is displaying it as an array. I’d like to instead just access the first items in this array so that it displays like this instead:

<div id="categoy">

However, when I use the index function, I get the following error:

execute of template failed: template: _default/list.html:33:24: executing "main" at <index .Params.categories 0>: error calling index: index of untyped nil

I’ve tried both

<div id="{{ index .Params.categories 0 }}">

and:

{{$category := index (.Params.categories) 0}}
<div id="{{ $category }}">

I know the array isn’t empty because .Params.categories returns [category]. Is there a different way I should be accessing the first item in this array?

Try this,

    {{ range .Pages }}
    <div id="{{ with .Params.categories }}{{ index . 0 }}{{ end }}">
        <p><strong><a href="{{ .Permalink }}">{{ .Title }}</a></strong></p>
        <p>{{ .Page.Description }}</p>
    </div>
    {{ end }}

About the ERROR, You need to make sure all pages executed using list.html has .Params.categories

1 Like

That worked! Thank you!

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.