Twig’s null-coa­lesc­ing operator (??)!

What's in a name? That which we call a null-coalescing operator by any other name would smell as sweet. Explore when and how to use the null-coalescing operator; simplify conditionals in your templates.

The Short Way

To simplify and shorten the logic in the code examples, we can use the null-coalescing operator – the operator with the longest, most complex name.

The null coalescing operator, basically says: "Give me the first operand in this expression, from left to right, that is both defined and not null. And, if all of the operands are undefined or null, just return null." – Michael Rog, from the QQ plugin docs

{{ variable ?? "Fallback" }}

{# Multiple conditions #}
{{ variable ?? otherVariable ?? null }}

The Long Way

A verbose if statement:

{% if variable is defined and variable is not null %}
	{{ variable }}
{% else %}
  Fallback
{% endif %}

{# Multiple conditions #}
{% if variable is defined and variable is not null %}

	{{ variable }}

{% else %}

	{% if otherVariable is defined and otherVariable is not null %}
		{{ otherVariable }}
	{% else %}
	  Your otherVariable doesn't exist.
	{% endif %}
  
{% endif %}

The ternary operator

{{ variable is defined and variable is not null ? variable : "Fallback" }}

{# Multiple conditions #}
{{ variable is defined and variable is not null ? variable : otherVariable is defined and otherVariable is not null ? otherVariable : "Fallback" }}

Twig's default filter

{{ variable|default('Fallback') }}

{# Multiple conditions #}
{{ variable|default(otherVariable|default('Fallback')) }}

Resources

Level up in Craft CMS with practical examples, snippets, and patterns.
Craft The Planet emails are sent out several times a week.