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

Published: 2019-11-25 22:31:28 -0500 -0500

Reading time: 1 mins (146 words)

Tags: hugo ternary isset variable

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.

About the Ham

Hi I'm Hamilton and I wrote / built this! I like doing lots of things, but mostly I like to build (and then share those buildings). Some things I'm currently building: art, software, and prose. To stay up-to-date with my latest buildings, subscribe to my email list or follow one of my many other accounts. #buildit #shipit #justhamit

comments powered by Disqus