Make sure a data value exists

I’m using .Site.Data.file.value to read some key data into my homepage template. This works fine but I want this usage to fail with an error on build if the value doesn’t exist. I’ve looked through the build flags and available template functions but I can’t find anything that “asserts” or “requires” a value to be a non-empty or non-nil value.

Does this exist already, or should I try to create a partial template which spits out an error?

Try this:

{{ with .Site.Data.file.value }}
  {{ $value := . }}
{{ else }}
  {{ errorf "WARN ERROR" }}
{{ end }}

That’s a clever way to use the with operator, but I’d like something even shorter since I tend to want to know when a value is missing before I deploy rather than maybe (or not) discovering it later.

I see that Go templates have an option missingkey=error which would solve this globally if it was set. It would be nice if this option could be set from the command line.

I could maybe create a preprocessor or something similar that would inject your code whenever an assert function was found?

errorf will stop the hugo build and throw error.

Any ERROR will also cause the build to fail (the hugo command will exit -1 ).

Yep, I made this partial template and put it in layouts/partials/require.html

{{ if . }}
  {{ . }}
{{ else }}
  {{ errorf "REQUIRE FAILED" }}
{{ end }}

Use it like this:

{{ partial "require" 123 }}

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