Twig icon indicating copy to clipboard operation
Twig copied to clipboard

This PR adds support for the optional chaining operator (?.) to Twig.

Open shokhaa opened this issue 10 months ago • 5 comments

This PR adds support for the optional chaining operator (?.) to Twig.

The optional chaining operator (?.) enables developers to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid.

Example usage:

{{ foo?.bar?.baz }}

This is equivalent to:

{{ foo.bar.baz is defined ? foo.bar.baz }}`

shokhaa avatar Mar 28 '25 15:03 shokhaa

./vendor/bin/simple-phpunit tests/Extension/OptionalChainingTest.php

Testing Twig\Tests\Extension\OptionalChainingTest ......S 7 / 7 (100%)

Time: 00:00.036, Memory: 10.00 MB

shokhaa avatar Mar 28 '25 15:03 shokhaa

So we doing this or nah?

Bilge avatar Jul 21 '25 01:07 Bilge

@fabpot What do you think of this idea? Today I had again a situation where this would have helped tremendously by doing something like {% if app.user.account.id == some.other.id %} and account being null.

ruudk avatar Aug 29 '25 10:08 ruudk

I'm dying for optional chaining in twig 🥵

ryanleichty avatar Sep 05 '25 18:09 ryanleichty