Twig空日期过滤器显示当前日期 [英] Twig null date filter shows current date

查看:113
本文介绍了Twig空日期过滤器显示当前日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据文档


如果传递给日期过滤器的值为null,它将返回
当前日期默认情况下。如果需要一个空字符串而不是
当前日期,请使用三元运算符:

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

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

The problem is the solution provided entails that we revisit all dates in the application and apply the ternary operation as we never want to show today's date instead of null.

是否可以覆盖默认日期过滤器?如果是这样,我该如何实施呢?我们正在使用带有symfony 2.7的树枝

is it possible to override the default date filter? if so how can I implement this. We're using twigs with symfony 2.7

推荐答案

在文档中,您可以覆盖现有过滤器:

As explained here in the doc, you can override an existing filter:


要重载已定义的过滤器,测试,运算符,全局
变量或函数,请在扩展名中对其进行重新定义,并尽可能晚地将其注册为
(顺序很重要)。

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());

这篇关于Twig空日期过滤器显示当前日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆