Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Twig have a null coalesce operator?

Tags:

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 %} 
like image 310
Adrian Macneil Avatar asked Nov 19 '12 10:11

Adrian Macneil


People also ask

Which is null coalescing operator?

The nullish coalescing operator ( ?? ) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined , and otherwise returns its left-hand side operand.

Why we use null coalescing operator?

operator is known as Null-coalescing operator. It will return the value of its left-hand operand if it is not null. If it is null, then it will evaluate the right-hand operand and returns its result. Or if the left-hand operand evaluates to non-null, then it does not evaluate its right-hand operand.


2 Answers

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 }} 
like image 79
Lindsey D Avatar answered Oct 22 '22 19:10

Lindsey D


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

{{ title|default("Default Title") }} 
like image 32
Molecular Man Avatar answered Oct 22 '22 19:10

Molecular Man