Essay record

Hugo: Set a variable using a ternary based on whether a variable is set or not

Record
Essay / / 1 min read / 151 words
Tags
hugo
On this page3 sections / +

DISCLOSURE: Some links may be affiliate links. Details

problem

I'm building a Hugo site and want to use a ternary expression in order to set the value of one of my variables based on whether my post has a parameter set or not, you know something like myVar = myConditional ? True : False. How can I do this?

solution

To do this, you can use a combination of cond and isset:

{{ $myVar := cond (isset .Params "PAGEPARAMETERNAME") .Params.PAGEPARAMETERNAME "DEFAULTVALUE" }}

In this example, $myVar gets set to .Params.PAGEPARAMETERNAME if .Params.PAGEPARAMETERNAME has been set to a value, otherwise it defaults to the value "DEFAULTVALUE". In this example, I'm returning a string, but you could of course return whatever other value you see fit.

did this help?

I regularly post about tech topics I run into. You can get a periodic email containing updates on new posts and things I've built by subscribing here.

Built with CloudSeed Rust