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

2023-09-06 23:50:04 作者:半亱梦见鉨

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?

推荐答案

求更详细的解决方案.

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

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

namespace MyAppAppBundleServices;

use SymfonyComponentHttpKernelHttpKernelInterface;
use SymfonyComponentHttpKernelEventGetResponseEvent;

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: MyAppAppBundleServicesTwigDateRequestListener
        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.