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

Date: 2019-11-25 | 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.

Want more like this?

The best / easiest way to support my work is by subscribing for future updates and sharing with your network.