Twig icon indicating copy to clipboard operation
Twig copied to clipboard

Only apply filter if not null

Open tacman opened this issue 1 year ago • 6 comments

@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') }} 

tacman avatar Oct 10 '24 13:10 tacman

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

{{ user.birthday ? user.birthday|date('Y-m-d') }}

smnandre avatar Oct 10 '24 20:10 smnandre

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

stof avatar Oct 11 '24 10:10 stof

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

smnandre avatar Oct 11 '24 12:10 smnandre

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 avatar Dec 08 '25 21:12 ecupaio

@ecupaio it is not about empty strings but about null. In PHP, new DateTimeImmutable(null) gives you the current date as well.

stof avatar Dec 09 '25 08:12 stof

Well, to be fair new DateTimeImmutable(null) also gives you a deprecation warning Passing null to parameter #1 of type string is deprecated.

smnandre avatar Dec 11 '25 00:12 smnandre