Hugo: Set a variable using a ternary based on whether a variable is set or not
Essay - Published: 2019.11.25 | 1 min read (151 words)
hugo
DISCLOSURE: If you buy through affiliate links, I may earn a small commission. (disclosures)
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.
Want more like this?
The best way to support my work is to like / comment / share this post on your favorite socials.
