Twig icon indicating copy to clipboard operation
Twig copied to clipboard

Add null-safe operator

Open felds opened this issue 1 month ago • 5 comments

Adds native support for Twig’s null-safe ?. operator so templates can traverse objects and arrays without defensive plumbing: {{ user?.address?.city }} now renders the value when present and stays silent when any hop is null.

?. reuses the existing GetAttrExpression operator, so it should have otherwise the same precedence and behavior as ..

Usage cases can be found in the tests: https://github.com/twigphp/Twig/blob/7d98d45f58df040f41a81f7f8d4cce6c42be781e/tests/ExpressionParserTest.php#L304-L343

Tests cover both the rendered output and the generated PHP.

Let me know if any tests are missing or if the implementation should be done any other way.

felds avatar Dec 01 '25 19:12 felds

This should fix issue #3260

felds avatar Dec 01 '25 19:12 felds

The failing tests are already present in twigphp:3.x. I have no idea what they refer to, and I don't think they are related to the changes in this PR.

felds avatar Dec 01 '25 20:12 felds

I've found the bug.

It was not in this repo, but it appeared when symfony/intl had some data updated.

I think testing for exact results from dependencies is not a good idea, since it would require updating the tests in this lib every time the depended package was updated, so I changed the test to expect at least N results instead of exactly N results.

felds avatar Dec 01 '25 20:12 felds

This is a duplicate of #4623

willrowe avatar Dec 01 '25 22:12 willrowe

@willrowe thanks for pointing that out. I wonder why that PR is stuck. It looks pretty good too...

felds avatar Dec 02 '25 20:12 felds

up

johndodev avatar Dec 14 '25 19:12 johndodev