如何在 Symfony2 中为 Twig 模板设置默认日期格式? [英] How can I set the default date format for Twig templates in Symfony2?

查看:27
本文介绍了如何在 Symfony2 中为 Twig 模板设置默认日期格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Twig 文档描述了如何为 date 过滤器设置默认日期格式:

Twig documentation describes how to set the default date format for the date filter:

$twig = new Twig_Environment($loader);
$twig->getExtension('core')->setDateFormat('d/m/Y', '%d days');

如何在 Symfony2 中全局进行此设置?

How can do this setting globally in Symfony2?

推荐答案

获取更详细的解决方案.

For a more detailed solution.

在您的包中创建一个可以包含事件侦听器的服务文件夹

in your bundle create a Services folder that can contain the event listener

namespace MyApp\AppBundle\Services;

use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;

class TwigDateRequestListener
{
    protected $twig;

    function __construct(\Twig_Environment $twig) {
        $this->twig = $twig;
    }

    public function onKernelRequest(GetResponseEvent $event) {
        $this->twig->getExtension('core')->setDateFormat('Y-m-d', '%d days');
    }
}

然后我们会希望 symfony 找到这个监听器.在 Resources/config/services.yml 文件中放入

Then we will want symfony to find this listener. In the Resources/config/services.yml file put

services:
    twigdate.listener.request:
        class: MyApp\AppBundle\Services\TwigDateRequestListener
        arguments: [@twig]
        tags:
            - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }

通过指定@twig 作为参数,它将被注入到 TwigDateRequestListener

by specifying @twig as an argument it will be injected into the TwigDateRequestListener

确保在 app/config.yml

imports:
    - { resource: @MyAppAppBundle/Resources/config/services.yml }

现在您应该可以跳过日期过滤器中的格式

Now you should be able to skip the format in the date filter as such

{{ myentity.dateAdded|date }}

它应该从服务中获取格式.

and it should get the formatting from the service.

这篇关于如何在 Symfony2 中为 Twig 模板设置默认日期格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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