Only apply filter if not null
@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') }}
The second part of the ternary is optional. The following will work the same
{{ user.birthday ? user.birthday|date('Y-m-d') }}
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
(just a precision on this case, not an opinion on the RFC)
This "feature" has caused me many a headache. You can use "now" to get the current date so there's no reason to convert empty string to now. If an empty string is applied, then it shouldn't be filled. I used the same solution as @smnandre but it's a bit tedious to write it for every single date. I have to codeswitch, literally, between lots of curly bars languages but Liquid, Hubl, and the like are all pretty logical on this DX.
@ecupaio it is not about empty strings but about null. In PHP, new DateTimeImmutable(null) gives you the current date as well.
Well, to be fair new DateTimeImmutable(null) also gives you a deprecation warning Passing null to parameter #1 of type string is deprecated.