Twig文档介绍了如何为date
过滤器设置默认日期格式:
$twig = new Twig_Environment($loader);
$twig->getExtension('core')->setDateFormat('d/m/Y', '%d days');
如何在Symfony2中全局设置此项?
为了获得更详细的解决方案。
在你的包中创建一个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中。imports:
- { resource: @MyAppAppBundle/Resources/config/services.yml }
现在您应该能够跳过日期过滤器中的格式,如下所示
{{ myentity.dateAdded|date }}
它应该从服务中获取格式。
从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
对于number_format
过滤器也是同样适用的。详情请参见:http://symfony.com/blog/new-in-symfony-2-7-default-date-and-number-format-configuration
在控制器中,您可以执行以下操作:
$this->get('twig')->getExtension('core')->setDateFormat('d/m/Y', '%d days');
\Twig_Environment
的twig
服务,并可以按上述描述进行设置。 - Philipp Rieber对于需要的人,你可以针对Symfony 4这样做。
twig:
...
date:
format: c
timezone: UTC
....
至少在我的Twig安装中(无框架),不存在名为“core”的扩展,我不得不使用Twig_Extension_Core
$twig->getExtension('Twig_Extension_Core')->setDateFormat($dateFormat);
在Twig版本v2.14.6中进行了测试
全局 Twig 配置选项可以在以下位置找到:
http://symfony.com/doc/2.0/reference/configuration/twig.html
在我看来,应该在这里添加“date_format”选项,因为对于大多数用户来说,使用Sonata Intl bundle 是过度的。
use Symfony\Component\HttpKernel\HttpKernelInterface;
;) - umpirsky