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.

1
2
3
4
5
6
7
8
{# 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:

1
2
3
4
{% do [first, last] = ['Fabien', 'Potencier'] %}

{{ first }} {# Fabien #}
{{ last }}  {# Potencier #}

Extra variables are set to null if there are more variables than values:

1
2
{% do [first, last, extra] = ['Fabien', 'Potencier'] %}
{# extra will be null #}

You can also skip values by leaving slots empty:

1
{% do [, last] = ['Fabien', 'Potencier'] %}

Object Destructuring

Use curly braces to destructure objects or mappings by property/key names:

1
2
3
4
{% 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.

1
2
3
4
5
{{ 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:

1
2
3
4
5
6
7
{% 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.

Published in #Releases #Twig