Search code examples
twigcoalesce

Does Twig have a null coalesce operator?


I'm using the Twig PHP template engine.

Is there an operator available which will output first non-empty value (coalesce)?

For example (using PHP pseudocode):

{{ title ?: "Default Title" }}

I know I could do something like this, but it's a bit long-winded:

{% if title %}{{ title }}{% else %}{{ "Default Title" }}{% endif %}

Solution

  • Yes, there is this filter called default. You can apply it to your code like below:

    {{ title|default("Default Title") }}