How to check if dynamically-named variable exists in context?

I’m having trouble making this piece of code work on all pages:

{{ if (isset .Site.Data.authors .Params.author) }} aaa {{ end }}

It does work fine on pages where I have author: <name> in the front matter, but it explodes with 128 stacktraces on the home page. I’m guessing that’s because there’s no value for .Params.author on the home page, and I was hoping this would work:

{{ if and (isset .Params "author") (isset .Site.Data.authors .Params.author) }}

alas, it doesn’t. Same deluge of errors, as if the engine was trying to interpret both sides of the and statement, instead of checking the first one and only moving to the second when the first returns true.

Any suggestions?

I had a similar problem. This may not be the correct answer but I used ‘with’ instead -

{{ with .Params.paramname }} stuff to include {{ end }}

However there may be a way to use isset correctly, too. I’m not sure of the syntax but the example in the docs is a bit different in terms of brackets and inverted commas from the one you’ve outlined?

Would your equivalent be:
{{ if isset .Params “author” }} aaa {{ end }}

What do you need to accomplish that’s made you use .Site.Data.authors in there? Are you needing to check the existence of both?

Of course… didn’t think of that – two separate ifs:

{{ if isset .Params "author" }}{{ if isset .Site.Data.authors .Params.author }}

Thanks @agh ! Not very clean, but it’s not the first time Go templates leave me feeling dirty.

1 Like

Another option is to use .IsHome:

{{ if .IsHome }}
  {{ if (isset .Site.Data.authors) }}
  ...
  {{ end }}
{{ else }}
  {{ if (isset .Params.authors) }}
  ...
  {{ else if (isset .Site.Data.authors) }}
  ...
  {{ end }}
{{ end }}