symfony - Twig 空日期过滤器显示当前日期

标签 symfony date twig

根据文档

If the value passed to the date filter is null, it will return the current date by default. If an empty string is desired instead of the current date, use a ternary operator:



http://twig.sensiolabs.org/doc/2.x/filters/date.html

问题是所提供的解决方案需要我们重新访问应用程序中的所有日期并应用三元运算,因为我们从不想显示今天的日期而不是 null。

是否可以覆盖默认日期过滤器?如果是这样,我该如何实现。我们在 symfony 2.7 中使用 Twig

最佳答案

如解释 here in the doc ,您可以覆盖现有过滤器:

To overload an already defined filter, test, operator, global variable, or function, re-define it in an extension and register it as late as possible (order matters).



如果 null,这是返回空字符串而不是当前日期的代码:
class DateEmptyIfNull extends Twig_Extension
{
    public function getFilters()
    {
        return array(
            new Twig_Filter('date', array($this, 'dateFilter')),
        );
    }

    public function dateFilter($timestamp, $format = 'F j, Y H:i')
    {
        $result = '';
        if($timestamp !== null)
        {
            $result = parent::dateFilter($timestamp, $format);
        }
        return $result;
    }
}

$twig = new Twig_Environment($loader);
$twig->addExtension(new DateEmptyIfNull());

关于symfony - Twig 空日期过滤器显示当前日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41551727/

相关文章:

javascript - 使用 Symfony2 将资源包含在 Twig Extension 中

php - Swift Mailer 和 Symfony2 - 假脱机中没有邮件

symfony - 如何将Tinymce与Symfony encore集成?

mysql - Doctrine - SQL 查询生成器 - 更新和连接?

java - 将区域设置日期字符串转换为时间戳。 Java/安卓

python - 如何使用时区感知日期过滤模型?

Symfony2 & Twig - 主题文件上传小部件

php - SessionHandler::write():父 session 处理程序未打开

javascript - 为什么 javascript date.setDate() 改变其他日期变量的值

symfony2 - twig - 如何从 Twig 模板内部渲染 Twig 模板