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

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

问题描述

According to the documentation

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.

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).

Here is the code to return an empty string instead of the current date if 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天全站免登陆