twigphp / Twig

Twig, the flexible, fast, and secure template language for PHP
https://twig.symfony.com/
BSD 3-Clause "New" or "Revised" License
8.18k stars 1.25k forks source link

Only apply filter if not null #4389

Open tacman opened 1 month ago

tacman commented 1 month ago

@fprochazka suggested a BC change so that the date filter returns blank instead of the current date.

Currently you have to do {{ user.birthday ? user.birthday|date('Y-m-d') : '' }} to avoid this.

Originally posted by @PrOF-kk in https://github.com/twigphp/Twig/issues/3951#issuecomment-2404415672

This got me thinking that a more generic solution would be to not apply filters to nulls, with a syntax similar to PHP's ?-> operator, like this;

 {{ user.birthday?|date('Y-m-d') }} 
smnandre commented 1 month ago

The second part of the ternary is optional. The following will work the same

{{ user.birthday ? user.birthday|date('Y-m-d') }}
stof commented 1 month ago

For a single filter, this works. For a longer expression, it is not the same (as it would force to apply filter twice, in the ternary condition and the ternary result expression

Also, omitting the else part of a ternary produces an empty string, not null

smnandre commented 1 month ago

(just a precision on this case, not an opinion on the RFC)