如何在Symfony2中设置Twig模板的默认日期格式?

Phi*_*ber 11 symfony twig

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

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

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

Leo*_*ley 20

有关更详细的解决方案.

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

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');
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

确保您在上面导入services.yml app/config.yml

imports:
    - { resource: @MyAppAppBundle/Resources/config/services.yml }
Run Code Online (Sandbox Code Playgroud)

现在,您应该能够跳过日期过滤器中的格式

{{ myentity.dateAdded|date }}
Run Code Online (Sandbox Code Playgroud)

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


Phi*_*ber 12

从Symfony 2.7开始,您可以在config.yml以下位置全局配置默认日期格式:

# app/config/config.yml
twig:
    date:
        format: d.m.Y, H:i:s
        interval_format: '%%d days'
        timezone: Europe/Paris
Run Code Online (Sandbox Code Playgroud)

number_format过滤器也是可能的.详细信息可以在这里找到:http://symfony.com/blog/new-in-symfony-2-7-default-date-and-number-format-configuration