Search code examples
twigtimber

Conditionally render twig variable with fallback


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 }}" />


Solution

  • 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 is undefined or empty, otherwise the value of the variable:

    Example https://twigfiddle.com/hsniy6/2

    <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 }}" />