Handling nil or (empty) array

I’ve checked the forums for similar issues but found none. I’m using a Frontend which renders my page frontmatter like this:

+++
applications = ["wireless"]
connections = []
cooling = []
downloads = []
date = "2018-05-17T09:22:19Z"
+++

or with the line downloads simply absent:

+++
applications = ["wireless"]
connections = []
cooling = []
date = "2018-05-17T09:22:19Z"

I’m trying to use a loop like this to say if I have any downloads or not:

  {{- range (where $.Site.Pages "Section" "products") -}}
  <ul>
    {{- if (isset .Params "downloads") and (isset .Params.downloads 0) -}}
      <li>{{ .Params.title }} ✅ HAS DOWNLOADS</li>
    {{- else -}}
      <li>{{ .Params.title}} ❌ NO DOWNLOADS</li>
    {{- end -}}
  </ul>
  {{- end -}}

But Im running into the issue that even an empty array seems to have (isset .Params.downloads 0) == true.

I’ve tried using {{ default .Params.downloads [] }} to make a fallback from nil to [] but it blows up on the [.

I just need a way to know if the array is really empty or not so I can print the title (.Params.title), and then loop over the .Params.downloads (which each contain a .url and .linktext) to print them.

I suppose I can do some, if not all the heavy lifting by pushing things into scratch maps, but it seems really inelegant and like I must really be missing something.

Thanks for a great tool, and for any tips anyone can offer.

Have you tried checking len instead? Something like

{{ if isset .Params "downloads" }}
    {{ if ( gt ( len .Params.downloads ) 0 ) }}
      <li>{{ .Params.title }} ✅ HAS DOWNLOADS</li>
    {{ else }}
      <li>{{ .Params.title}} ❌ NO DOWNLOADS</li>
    {{ end }}
{{ end }}

with is your friend here https://gohugo.io/functions/with

No. Not sure how that would be “the same”. You would have to look at go-18n (the package we use) for some tools to handle translation files.

lang.Merge also to merge missing translations of content. I would like to do this with translation string.
Something like
{{ i18n "readingTime" .ReadingTime | lang.Merge (i18n "readingTime" .ReadingTime "fr") | lang.Merge (i18n "readingTime" .ReadingTime "en") }}

OK, I see.

You will, I think, currently get the “default translation” if a language is missing a string. But you cannot specify a order. I don’t think that is easily implemented, but I would be happy to be proven wrong.

1 Like