Add support for the optional chaining operator ?. that is available in:
{# Before #}
{{ foo.bar.baz is defined ? foo.bar.baz }}
{# After #}
{{ foo?.bar?.baz }}
it should even be the default behaviour.
-1 for being the default behavior. That would make it a lot harder to identify mistakes (typo in a property name) when you don't expect it to be optional.
-1 for being the default behavior. That would make it a lot harder to identify mistakes (typo in a property name) when you don't expect it to be optional.
In php, there is tools like phpstan returning error for
$foo->getBar()->getBaz()
if getBar can be null. But there is nothing like this for twig. So mistake is easier to make.
I find sad the fact that
{% if foo.bar.baz %}
...
{% endif %}
throw an exception and display an error 500 in production when foo.bar is null.
This should be user-first and not dev-first.
What about a strict mode, enable in dev ?
Well, first, it does not throw an exception by default in production, as strict_variables is opt-in and will make . return null for non-existent attributes.
If what you want is to have everything optional in prod and strict in dev, Twig already has that feature since the 1.0 release (and probably even before in some 0.x releases).
To me, the benefit of a ?. operator would be that it could be used even in strict mode
Well, first, it does _not_ throw an exception by default in production, as
strict_variablesis opt-in and will make.returnnullfor non-existent attributes.If what you want is to have everything optional in prod and strict in dev, Twig already has that feature since the 1.0 release (and probably even before in some 0.x releases).
To be, the benefit of a
?.operator would be that it could be used even in strict mode
Oh sorry, didn't know that. That's great. I agree with you then.
Would be cool to have this feature 馃憤
Null-safe operator was introduced in PHP 8 https://wiki.php.net/rfc/nullsafe_operator
Most helpful comment
-1 for being the default behavior. That would make it a lot harder to identify mistakes (typo in a property name) when you don't expect it to be optional.