How to make sure index exists

I have an author system implemented where the frontmatter of pages includes things like this:

---
authors:
  - bruno-amaral
  - pedro-rodrigues
---

My problem is that not every page has an author, and some include only one author. The first one is always the main to display in the frontend.

I was trying to use {{ with (index .Params.authors 0) }} but I still get an error executing "shortcodes/blog-6.html" at <index .Params.authors 0>: error calling index: index of untyped nil

{{ $ref := (.Get "ref") }}
{{ $page := "" }}
{{ range .Page.Sites }}
  {{ if eq (print (.GetPage $ref).File) $ref }}
    {{ $page = (.GetPage $ref) }}
  {{ end }}
{{ end }}



{{ with $page }}
  {{ $author := "" }}
  {{ $avatarimage := ""}}
  {{ with (index .Params.authors 0) }}
   {{ $author = $.Site.GetPage (printf "authors/%s/" (index .Params.authors 0) )}}
  {{ else }}
default author:
    {{ $author = $.Site.GetPage "authors/bruno-amaral/" }}
  {{ end }}
{{end }}

This seems to work:

{{ if gt (len .Params.authors) 0 }}

but breaks if the file contains this:

---
authors:
  - 
draft: false
---

` error calling len: reflect: call of reflect.Value.Type on zero Value`
{{ with .Params.authors }}
  {{ $author = $.Site.GetPage (printf "authors/%s" (index . 0)) }}
{{ else }}

Or, if you need to defend against an empty slice:

{{ with .Params.authors }}
  {{ with index . 0 }}
    {{ $author = $.Site.GetPage (printf "authors/%s" .) }}
  {{ end }}
{{ else }}
1 Like

Much easier than I thought, thank you @jmooring !

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