[英]Symfony2: How can I set twig |date(“d F, Y”) filter to output months in Swedish?
我的twig模板中的| date(“d F,Y”)過濾器出現問題。
我想用瑞典語輸出月份。 我試過在我的parameters.yml文件中設置“locale:sv”,但是沒有效果。
它在我從Symfony 2.1升級到2.3之前一直在工作,所以我認為這可能與它有關。
有關如何解決此問題的任何想法?
Twig Intl擴展
您可以使用fabpot官方Twig擴展存儲庫中的Twig Intl Extension 。
它提供了一個本地化的日期過濾器,可以像這樣使用:
{{ date | localizeddate('full', 'none', app.request.locale ) }}
使用app.request.locale
作為當前語言環境的第三個參數或只是'sv'
。
集成到您的項目中
使用以下命令添加composer.json
的官方擴展:
composer require twig/extensions:1.0.*@dev
composer update twig/extensions
config.yml
#enable intl extensions
services:
twig.extension.intl:
class: Twig_Extensions_Extension_Intl
tags:
- { name: twig.extension }
小建議:
另一個方便的擴展是Text擴展提供截斷 ,...等過濾器
services:
twig.extension.text:
class: Twig_Extensions_Extension_Text
tags:
- { name: twig.extension }
|date
filter使用不支持語言環境的DateTime::format
函數。 看到這個問題並編寫自己的枝條擴展。
我將對@nifr發布的解決方案進行補充。
要使用您的日期格式,請安裝Twig Intl Extension,然后您可以使用:
{{ date|localizeddate('none', 'none', app.request.locale, null, 'dd MMMM, yyyy') }}
我的示例中的最后一個參數是日期格式 - 這是一個文檔: http : //userguide.icu-project.org/formatparse/datetime
這是Twig Intl Extension文檔: https : //twig-extensions.readthedocs.io/en/latest/intl.html
我不太喜歡Twig Intl擴展,它對我的用例感覺有點臃腫,因此我采用了不同的方法。 在我們的應用程序中,我們擴展了DateTime對象並重載了format
函數,以使用PHP的strftime
函數轉換日期。
在使用此方法之前,應該考慮以下幾點:
DateTimeInterface
但是期望\\DateTime
對象 這是DateTime類:
YourNameSpace;
class DateTime extends \DateTime {
public static function createFromFormat($format, $time, $timezone = null) {
$dateTime = parent::createFromFormat($format, $time, $timezone);
// we want to return a <YourNameSpace>\DateTime instead of a 'normal' DateTime, thus we have to instantiate one
// note that this returns `null` instead of `false` so you can use nullable return types `?DateTime` and the `??` operator
return $dateTime && $dateTime->format($format) == $time ? (new DateTime())->setTimestamp($dateTime->getTimestamp()) : null;
}
const FORMAT_LOCALE_MAP = [
'F' => '%B', // full textual representation of a month, such as January or March
'M' => '%b', // short textual representation of a month, three letters
'l' => '%A', // full textual representation of the day of the week
'D' => '%a' // short textual representation of a day, three letters
// add any other if your application needs it
];
public function format($format): string {
$formattedDate = parent::format($format);
// localize string
foreach(self::FORMAT_LOCALE_MAP as $dateFormat => $strftimeFormat) {
if(strpos($format, $dateFormat) !== false) {
$formattedDate = str_replace(parent::format($dateFormat), strftime($strftimeFormat, $this->getTimestamp()), $formattedDate);
}
}
return $formattedDate;
}
}
然后在你的前端控制器(即public/index.php
)中設置你的語言環境:
setlocale(LC_ALL, 'nl_NL');
現在在Twig模板中,DateTime格式化的任何位置:
// start is an instance of your extended DateTime object
{{ start.format('D d M')|capitalize }}
// Do 06 dec
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.