【发布时间】:2012-03-27 08:43:43
【问题描述】:
Twig 文档描述了如何为 date 过滤器设置默认日期格式:
$twig = new Twig_Environment($loader);
$twig->getExtension('core')->setDateFormat('d/m/Y', '%d days');
如何在 Symfony2 中进行全局设置?
【问题讨论】:
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
确保您在 app/config.yml 顶部导入 services.yml
imports:
- { resource: @MyAppAppBundle/Resources/config/services.yml }
现在您应该可以跳过日期过滤器中的格式
{{ myentity.dateAdded|date }}
它应该从服务中获取格式。
【讨论】:
use Symfony\Component\HttpKernel\HttpKernelInterface; ;)
从 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 服务,并且可以进行上述设置。
对于 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 捆绑包对大多数用户来说是多余的。
【讨论】: