Essay - Published: 2019.11.26 | hugo | isset | ternary | variable |
DISCLOSURE: If you buy through affiliate links, I may earn a small commission. (disclosures)
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?
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.
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.
The best way to support my work is to like / comment / share for the algorithm and subscribe for future updates.