簡體   English   中英

如何在Symfony3中獲取TWIG自定義過濾器參數?

[英]How to get TWIG custom filter parameters in Symfony3?

我只是嘗試根據示例制作一個簡單的TWIG過濾器

SRC / BlogBu​​ndle /服務/ 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 }

並在一些template.twig中使用它

{{ comment.date|ago }}

正確調用了回調函數(agoFiler),並顯示了其輸出,但是我無法獲取過濾器參數。 在上面的示例中,盡管comment.date是一個確定的日期,但我總是得到NULL返回(默認TWIG的日期過濾器可以正常工作)。 如何在agoFilter函數中獲取comment.date?

更新: {{ 5|ago }}按預期返回integer{{ [5]|ago }}返回array ,但是{{ comment.date|ago }}{{ comment.getDate()|ago }}仍返回NULL ,盡管{{ comment.date|date('dmY') }}返回正確的日期。

非常非常非常奇怪的事情。 我不知道該怎么做,但是仔細閱讀了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構造函數卻很好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM