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 %}
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.
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.
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") }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With