How to get TWIG custom filter parameters in Symfony3?

787 Views Asked by At

I just tried to make a simple TWIG filter according to example

src/BlogBundle/Services/TwigExtension.php

<?php

namespace BlogBundle\Services;

class TwigExtension extends \Twig_Extension {
    public function getFilters() {
        return [
            new \Twig_SimpleFilter('ago', [$this, 'agoFilter']),
        ];
    }

    public function agoFilter($date) {
        return gettype($date);
    }

    public function getName() {
        return 'twig_extension';
    }
}

services.yml

services:
    app.twig_extension:
        class: BlogBundle\Services\TwigExtension
        public: false
        tags:
            - { name: twig.extension }

and use it in some template.twig

{{ comment.date|ago }}

The callback function (agoFiler) is called correctly and its output is shown, but I cannot get filter parameters. In example above I always get NULL returned, although comment.date is a date for sure (default TWIG's date filter works fine for it). How can I get comment.date in agoFilter function?

UPDATE: {{ 5|ago }} returns integer as supposed, {{ [5]|ago }} returns array, but {{ comment.date|ago }} and {{ comment.getDate()|ago }} still return NULL, though {{ comment.date|date('d.m.Y') }} returns correct date.

1

There are 1 best solutions below

2
On

Very, very, very strange thing. I did not understood how it could be, but after a mindful reading of TWIG's default date filter, I found there a solution:

public function agoFilter(\Twig_Environment $env, $date, $format = null, $timezone = null) {
    if ($date === null) $date = new \DateTime($date);
    return $date->format('d.m.Y');
}

That works fine, though it seems, that I pass null to DateTime constructor.