Logical OR operator assignment

Just wanted to share a quick tip, that i find very useful and need a lot.

Coming from JavaScript x = x || y or x = x && y is a appreciated shot form. Until recently when working with Hugo I had no idea how to translate this to go templates. Today it somehow made sense and I love it.

Use case

If you are faced with the situation that you have optional values, that can only be assigned when existing, I mostly assigned a default value and than checked if the optional parameter is available:

{{ $color := .Site.Params.color }}
{{ with .Params.color }}
  {{ $color = . }}
{{ end }}

This takesup 4 lines just to assign an optional value or its fallback. So I found this:

{{ $color := or .Params.color .Site.Params.color }}

You can even go so far as wrapping the assignment:

{{ $color := (or .Params.color .Site.Params.color) | safeCSS }}


{{ $result := or $valA $valB }}

$valA is assigned when it has a truthy value, $valB is assigned when $valA is falsy (empty string, undefined/nil or false).

Same can be done with the logical AND operator:

{{ $result := and $valA $valB }}

But $valB is only getting assigned assigned when $valA is truthy.

Nice writeup!

For this particular use case you can also use:

1 Like