1

我只是尝试根据示例制作一个简单的 TWIG 过滤器

src/BlogBu​​ndle/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';
    }
}

服务.yml

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

并在一些 template.twig 中使用它

{{ comment.date|ago }}

正确调用回调函数(agoFiler)并显示其输出,但我无法获取过滤器参数。在上面的示例中,我总是返回 NULL,尽管 comment.date 肯定是一个日期(默认 TWIG 的日期过滤器可以正常工作)。如何在 agoFilter 函数中获取 comment.date?

更新:按预期返回,{{ 5|ago }}返回,但仍然返回,尽管返回正确的日期。integer{{ [5]|ago }}array{{ comment.date|ago }}{{ comment.getDate()|ago }}NULL{{ comment.date|date('d.m.Y') }}

4

1 回答 1

1

非常非常非常奇怪的事情。我不明白它是怎么回事,但是在仔细阅读了 TWIG 的默认日期过滤器之后,我发现了一个解决方案:

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

这很好,虽然看起来,我将 null 传递给 DateTime 构造函数。

于 2016-01-30T20:06:25.860 回答