Dealing With Undefined Params and Undefined Go Template Variables in Hugo

blog image

In the realm of static site generation, Hugo stands out as a powerful, versatile choice. As with any tool, however, it has its own nuances and limitations. Among these, one that is often encountered is Hugo’s handling, or lack thereof, of undefined parameters. For those who have grappled with this issue, we’re pleased to bring to you a solution that mitigates this challenge.

The Challenge

At the heart of the matter is Hugo’s current handling of parameters. If you use a parameter in your templates that isn’t defined in your content files, Hugo could either throw errors or result in unexpected output, thereby impeding seamless website generation. I know Hugo has an ‘isset’ function, but I was looking for a solution I could also apply to Go Template Variables.

Possible Solutions

After thorough exploration and testing, a practical solution was identified. Hugo’s built-in default function, which serves as a fallback when a parameter is undefined, proved to be the answer. This approach essentially prescribes a default value to a parameter in the event it isn’t explicitly defined.

Here’s what the syntax looks like:

{{ .Params.yourParam | default "defaultValue" }} -> defaultValue

With this implementation, if .Params.param is undefined, Hugo will default to the provided string “defaultValue”.

Considerations: While the default function proves a robust workaround, it comes with some considerations. The selection of the default value demands careful thought to ensure that it neither disrupts the site’s functionality nor detracts from its aesthetics.

Alternative Strategies

While the default function is the recommended solution to this problem, there are other potential strategies:

Checking for parameter existence: Hugo allows for a check of parameter existence before its use with the with keyword:

{{ with .Params.categories }}
    <!-- Code that uses the parameter goes here -->
{{else}}
    <!-- Alternative code goes here -->
{{ end }}

My favorite strategy:

Compare the param with known undefined variable: Something fun I noticed, is while Hugo doesn’t support ‘undefined’ or ‘null’ as the value, it does do this under the hood. If you compare the Params with another params which isn’t clearly defined, it understands what you want.

{{$undefined := .Params.randomUndefinedVariable}} /* Ensure this variable actually doens't exist. */
{{eq .Params.categories $undefined}} /* Now compare */
{{$NewPageVariable := $undefined}}  /* Set a new variable as undefined */

The best part about the above approach, is that you can still work with the cond function and even set other Go Template variables as $undefined by default.

Conclusion:

What’s your favorite solution? Let me know! 👀

Liked this story? Share it with someone who needs to see it 👇