phpsymfonytwigtwig-extensiontwig-filter

Call built-in filter in custom Twig filter


When setting up a custom Twig filter (see https://symfony.com/doc/current/templating/twig_extension.html ), how can I call an existing Twig filter in my custom function?

https://stackoverflow.com/a/41551944/1668200 suggests parent::dateFilter($timestamp, $format); but that isn't working:

Attempted to call an undefined method named "dateFilter" of class "Twig_Extension".


Solution

  • The example you've linked is actually incorrect. The proper way would be like this,

    class DateEmptyIfNull extends Twig_Extension // or: extends AbstractExtension
    {
        public function getFilters()
        {
            return array(
                new TwigFilter('date', [ $this, 'dateFilter'], ['needs_environment' => true, ]),
            );
        }
    
        public function dateFilter(Twig_Environment $env, $timestamp, $format = 'F j, Y H:i')
        {
            return $timestamp === null ? '' : twig_date_format_filter($env, $timestamp, $format);
        }
    
    }