Is it possible to attempt to render a variable and use a fallback if it's falsy?
I've tried the following with no luck:
<img src="{{ fields.icon.url || post.thumbnail.src }}" />
<img src="{{ fields.icon.url or post.thumbnail.src }}" />
Using or
will cause the resulting output to become a boolean value 1
or 0
.
Instead you can use the default
filter
The
default
filter returns the passed default value if the value isundefined
orempty
, otherwise the value of the variable:
<img src="{{ fields.icon.url|default(post.thumbnail.src) }}" />
Alternatively you can also use the ternary operators ?:
or the null coalescing ??
operator.
The ternary operator ?:
is the equivalent to is not empty
.
The null coalescing operator will only work when the leading variable is undefined
, null
and is the equivalent to is same as(null)
.
<img src="{{ fields.icon.url ?: post.thumbnail.src }}" />
<img src="{{ fields.icon.url ?? post.thumbnail.src }}" />