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

11

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

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

如何在Symfony2中全局设置此项?

6个回答

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');
    }
}

然后我们希望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 }
通过在参数中指定@twig,它将被注入到TwigDateRequestListener中。
确保在app/config.yml的顶部导入services.yml。
imports:
    - { resource: @MyAppAppBundle/Resources/config/services.yml }

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

{{ myentity.dateAdded|date }}

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


很酷,谢谢!顺便说一下,未使用的use语句use Symfony\Component\HttpKernel\HttpKernelInterface; ;) - umpirsky

14

很遗憾,无法区分日期和日期时间对象,因此无法为日期和日期时间设置不同的格式,据我所知... - Vincent Pazeller

2

在控制器中,您可以执行以下操作:

$this->get('twig')->getExtension('core')->setDateFormat('d/m/Y', '%d days');

1
这也是我的第一个想法。我更喜欢在config.yml中或使用监听器设置全局设置,以便在整个项目中都有效。我只是在我的问题中添加了“全局”以使其更清晰。 - Philipp Rieber
无法通过在config.yml中添加配置来完成此操作。据我所知,TwigBundle不会公开核心扩展。是的,您可以添加请求监听器来实现这一点。 - Mun Mun Das
当在请求监听器中进行设置时,全局设置可以正常工作。我正在注入类\Twig_Environmenttwig服务,并可以按上述描述进行设置。 - Philipp Rieber
你能提供一个如何通过config.yml处理默认日期格式的示例吗? - Rvanlaak

1

对于需要的人,你可以针对Symfony 4这样做。

twig:
    ...
    date:
        format: c
        timezone: UTC
    ....

0

至少在我的Twig安装中(无框架),不存在名为“core”的扩展,我不得不使用Twig_Extension_Core

$twig->getExtension('Twig_Extension_Core')->setDateFormat($dateFormat);

在Twig版本v2.14.6中进行了测试


-1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接