Missing frontmatter element causes

Given these posts

title: Test Post A
title: Test Post B
  - "DrQZXoHlqQI"

This snippet from my template generates errors for posts that do not have a videoEmbeds element defined.

Here is the error:

Failed to render pages: render of "page" failed: "<path_to>/single.html": execute of template failed: template: _default/single.html:60:32: executing "main" at <len .Params.videoEmbeds>: error calling len: reflect: call of reflect.Value.Type on zero Value
<h4 class="f4">Videos ({{ len .Params.videoEmbeds }})</h4>

Is this the only solution? (Other than defining an empty videoEmbeds member in all my posts?

<h4 class="f4">Videos
  {{if isset .Params "videoEmbeds"}}
    ({{ len .Params.videoEmbeds }})

Well, basically yes — at least for now.

It is very much rooted in the way Go templates work; the general rule of Go templates is that you can’t simply pass a nil (be it a slice, a string, a map, or whatever) to a template or a function and expect it to fail gracefully (unless it’s a with or some other function specifically designed to deal with possibly nil values).

With is your friend.

{{ with .Params.videoEmbeds }}{{ len . }}{{ else }}0{{ end }}
1 Like

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