如何在树枝模板中正确打印日期?

时间:2014-01-12 01:15:40

标签: symfony twig

我的一些表包含日期字段,一些值设置为:'0000-00-00',当我尝试在这样的树枝模板中打印日期时:

{{ entity.date | date('m/d/Y') }}

我得到以下异常:

An exception has been thrown during the rendering of a template ("DateTime::__construct(): Failed
to parse time string (-001-11-30T00:00:00-06:00) at position 7 (-): 
Double timezone specification") in MGAdminBundle:Customers/Partials:_estimates.html.twig at line 12. 
  • 如何处理这些日期的打印?
  • 如果我将'date'类型映射到字符串会不会更好?

1 个答案:

答案 0 :(得分:1)

日期过滤器接受字符串(它必须采用strtotime函数支持的格式),DateTime实例, enter link description here

您可以创建树枝扩展名

<?php 


use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Bundle\TwigBundle\Loader\FilesystemLoader;
use CG\Core\ClassUtils;


class PostExtension extends \Twig_Extension{

    protected $loader;
    protected $controller;

    public function __construct(FilesystemLoader $loader)
    {
        $this->loader = $loader;
    }

    public function setController($controller)
    {
        $this->controller = $controller;
    }

    /**
     * {@inheritdoc}
     */
    public function getFunctions()
    {
        return array(
            'dateFormater' => new \Twig_Function_Method($this, 'dateFormater', array('is_safe' => array('html'))),
        );
    }

    public function dateFormater($dateTime){

        $now = new \DateTime('NOW');
        return $now->format( 'd-m-Y' ); // any other format !!               
    }

    /**
     * Returns the name of the extension.
     *
     * @return string The extension name
     */
    public function getName()
    {
        return 'some_extension';
    }


}

现在将其添加为服务!

 <services>
        <service id="twig.extension.postExtension" class="Project\PostBundle\Twig\Extension\PostExtension" public="false">
            <tag name="twig.extension" />
            <argument type="service" id="twig.loader" />
        </service>

        <service id="project.post.listener" class="Project\PostBundle\EventListener\ControllerListener">
            <tag name="kernel.event_listener" event="kernel.controller" method="onKernelController" />
            <argument type="service" id="twig.extension.postExtension" />
        </service>
    </services>

所以最后你可以将它用作你的树枝代码中的过滤器

{{ dateFormater(entity.date) }}
享受!