`cond` operator works different from if-else

For $page which can have custom parameter “customUrl” I need to create $url for anchor:

  • if customUrl is set and not empty then it becomes resulting $url
  • if customUrl not set or empty then $url set to some $defaultUrl

Works fine with empty (“”) or absent customUrl:

$url := ""
{{ if $page.Params.customUrl }}
    {{ $url = $page.Params.customUrl }}
{{ else }}
    {{ $url = $defaultUrl }}
{{ end }}

also works fine:

{{ $url := $page.Params.customUrl }}
{{ if not $url }}
    {{ $url = $defaultUrl }}
{{ end }}

Means absent parameter or empty parameter implicitly converted to boolean false. But when trying to use compact ternary operator cond

{{ $url = cond $page.Params.customUrl $page.Params.customUrl $defaultUrl }} 

getting error: wrong type for value; expected bool; got string

So there is no implicit type conversion. This difference messing up things, because ternary operator usually serves as compact alternative to if-else. Of course there is right way to use combination of not, isset and eq but then cond becomes far not so compact. But may be there is less bulky way to use cond in case like this?

Yes, cond only supports boolean true or false condition.

Alternative way to create fallback-value is using or:

{{ $url := or $page.Params.customUrl $defaultUrl }}

Also, one of the reason to avoid cond, because both return expressions will be evaluated.

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.