Does Twig have a null coalesce operator?

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


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

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

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

Tags:

Coalesce

Twig