How to get the name of the first category?

Hi,

I’ve read the Hugo functions and the Go documentation for arrays/slices, but cannot get the name of a page’s first category. Here’s one of the things I tried:

{{ .Params.categories[0] }}

Something like this:

{{ index .Params.categories 0 }}

Thank you!

For others, I’ve implemented it like this:

{{ if isset .Params "categories" }}
    • {{ index .Params.categories 0 }}
{{ end }}

Is there by the way also a way to check the length before accessing? For example (pseudo code):

{{ if .Params.categories.Length ">" 0 }}
  {{ index .Params.categories 1 }}
{{ end }}

That would prevent ‘index out of range’ errors.

{{ if gt (len .Params.categories) 0 }}
  {{ index .Params.categories 0 }}
{{ end }}
1 Like