29

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 %}
Adrian Macneil
  • 13,017
  • 5
  • 57
  • 70
  • 4
    The answer is provided by @molecularman but I want to let you know you can make your last example shorter: `{{ title ? title : 'Default Title' }}` – Wouter J Nov 19 '12 at 20:38

3 Answers3

57

The null-coalescing operator was formally introduced in Twig 1.24 (Jan. 25, 2016).

* adding support for the ?? operator

Which means it's now possible to do this...

{{ title ?? "Default Title" }}

You can even chain them together, to check multiple variables until a valid non-null value is found.

{{ var1 ?? var2 ?? var3 ?? var4 }}
Lindsey D
  • 2,437
  • 3
  • 17
  • 20
33

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

{{ title|default("Default Title") }}
Molecular Man
  • 22,277
  • 3
  • 72
  • 89
  • 3
    This is incorrect, `default` performs a boolean-like evaluation, which e.g. means the non-null-value `false` will also be replaced with the default value. As of Twig v1.24 better use the `??` operator. See https://twig.symfony.com/doc/2.x/tests/empty.html – Hudri Oct 29 '20 at 17:50
  • Thanks for the info. However, the link to the documentation that you shared is broken. Try this instead: https://twig.symfony.com/doc/2.x/filters/default.html – Matthew Setter Apr 15 '23 at 06:41
6

As of Twig 1.12.0, it does have the ?: operator, but it's not really "null coalescing". It checks for truthiness, not just nulls, thus 0 ?: 1 would come out 1.

Documentation

mpen
  • 272,448
  • 266
  • 850
  • 1,236