Twig: DATE filter

Created on 3 Feb 2016  路  9Comments  路  Source: twigphp/Twig

The date filter of a null variable gives the date of today. I think that the filter should return a null or an empty string, because you display a data which is corrupted.

EX

{{ null | date('d-m-Y') }} return the date of today

Behavior Change Bug

Most helpful comment

You can still overwrite this behavior to fit your personal needs.

        $twig->addFilter(new \Twig_SimpleFilter('date', function($date) {
            return is_null($date) ? null : date($date);
        }));

All 9 comments

Changing this would be a BC break, so it is not possible

And by the way, this behaviour is documented:

If the value passed to the date filter is null, it will return the current date by default.

Ok, thank you, but I still think that the behaviour is illogic. I close the issue.

For now {{ null is empty ? '' : date('d-m-Y') }}

Maybe add an arguments like empty_on_null or something?
date is the only filter (it seems) that returns a result on null, all other filters simple return an empty string.

I find this logic pretty weird as well. It basically requires adding the is empty thing any time it is used

You can still overwrite this behavior to fit your personal needs.

        $twig->addFilter(new \Twig_SimpleFilter('date', function($date) {
            return is_null($date) ? null : date($date);
        }));

@ninsuo except that your implementation for non-null values is wrong, as it supports far less things that the core filter

Changing the current behavior is not possible as it would be a BC break. I'm not convinced about adding an argument as it would make it more verbose that the current workarounds. So, let's close.

Another option is to deprecate passing null entirely.

Was this page helpful?
0 / 5 - 0 ratings