我想用德语显示TWIG中的日期。
{{ event.beginnAt |date('l d.m.Y')}}
但输出为"2013年6月28日星期五"。
我应该在哪里使用用德语显示日期的setlocale函数?
您需要启用trick-intl扩展(它需要在php中启用intl函数),然后只需使用:
{{ event.beginAt | localizeddate('full', 'none', locale) }}
编辑:
如果你只想本地化一天的名称,你可以创建自己的Twig扩展:
src/Acme/Bundle/DemoBundle/Twig/DateExtension.php
namespace Acme'Bundle'DemoBundle'Twig;
class DateExtension extends 'Twig_Extension
{
public function getFilters()
{
return array(
new 'Twig_SimpleFilter('intl_day', array($this, 'intlDay')),
);
}
public function intlDay($date, $locale = "de_DE")
{
$fmt = new 'IntlDateFormatter( $locale, 'IntlDateFormatter::FULL, 'IntlDateFormatter::FULL, 'Europe/Berlin', 'IntlDateFormatter::GREGORIAN, 'EEEE');
return $fmt->format($date);
}
public function getName()
{
return 'date_extension';
}
}
然后在服务中注册。yml
src/Acme/Bundle/DemoBundle/Resources/config/services.yml
parameters:
acme_demo.date_extension.class: Acme'Bundle'DemoBundle'Twig'DateExtension
services:
acme_demo.twig.date_extension:
class: %acme_demo.date_extension.class%
tags:
- { name: twig.extension }
在你的Twig模板中,你可以只使用:
{{ event.beginAt|intl_day }} {{ event.beginAt|date('d.m.Y') }}
为了实现这一点,我使用了SonataIntlBundle,它公开了一些用intl格式化的trick函数。
示例:
{{ date_time_object | format_datetime(null, 'fr', 'Europe/Paris',
constant('IntlDateFormatter::LONG'), constant('IntlDateFormatter::SHORT')) }}
将输出
'1 février 2011 19:55'
我使用了一种更简单的方法,因为我强制使用php执行上下文的本地,然后用format_datetime替换日期函数。记住要查看支持的模式,因为它们与strftime不同。你在SonataIntlBundle上有一个链接。
您可以使用setlocale()
和strftime()
,使用Symfony特定的东西可能会产生开销。