Twig 3.23: Introducing new operators and destructuring support
We're excited to announce the release of Twig 3.23, which has new features that enhance expressiveness and ease of use. This version introduces the assignment operator, destructuring capabilities, a null-safe operator, and strict comparison operators. Let's dive into what's new!
Assignment Operator (=)
The assignment operator allows you to set variables directly within expressions. This is particularly useful for concise code and can replace the short-form of the set tag in many cases.
{# Assign and output the result #}
{{ b = 1 + 3 }}
{# Assignments can be chained #}
{% do a = b = 'foo' %}
{# Assignment can be used inside other expressions #}
{% do a = (b = 4) + 5 %}
This operator has right associativity and can be used in various contexts to make your templates more streamlined.
Destructuring
Destructuring lets you extract values from sequences, mappings, and objects in a single operation, making it easier to work with complex data structures.
Sequence Destructuring
Use square brackets to destructure sequences:
{% do [first, last] = ['Fabien', 'Potencier'] %}
{{ first }} {# Fabien #}
{{ last }} {# Potencier #}
Extra variables are set to null if there are more variables than values:
{% do [first, last, extra] = ['Fabien', 'Potencier'] %}
{# extra will be null #}
You can also skip values by leaving slots empty:
{% do [, last] = ['Fabien', 'Potencier'] %}
Object Destructuring
Use curly braces to destructure objects or mappings by property/key names:
{% do {name, email} = user %}
{{ name }} {# user.name #}
{{ email }} {# user.email #}
This uses the dot operator under the hood, so it's equivalent to name = user.name.
Null-Safe Operator (?.)
The null-safe operator (?.) allows safe navigation through potentially null values, returning null instead of throwing an exception if the left operand is null.
{{ user?.name }}
{# returns null if user is null, otherwise returns user.name #}
{{ user?.address?.city }}
{# can be chained for safe navigation #}
This is perfect for avoiding null reference errors in your templates.
Strict Comparison Operators (=== and !==)
These operators provide strict equality and inequality checks, equivalent to the same as and not same as tests.
Examples:
{% if a === b %}
{# true if a and b are the same type and value #}
{% endif %}
{% if a !== b %}
{# true if a and b are not the same type and value #}
{% endif %}
Use these when you need to ensure both value and type match exactly.