我在树枝中显示一个 DateTime 对象,如下所示:
<td>{{ transaction.getDate|date("F - d - Y") }}</td>
现在我希望月份可以翻译, 例如
April - 20 - 2012
应显示为:Avril - 20 - 2012
我可以这样做吗? 如果是的话,怎么办?
我正在开发 Symfony2。
或使用国际分机:
{{ "now"|localizeddate('none', 'none', app.request.locale, "Europe/Paris", "cccc d MMMM Y") }}
会给你类似的东西:
jeudi 25 février 2016
要启用 symfony 2,请添加到composer :
composer require twig/extensions
并通过服务激活过滤器:
services:
twig.extension.intl:
class: Twig_Extensions_Extension_Intl
tags:
- { name: twig.extension }
您可以获取月份部分,然后翻译它:
{% set month = transaction.getDate|date('F') %}
{% set dayAndYear = transaction.getDate|date('d - Y') %}
{{ '%s - %s'|format(month|trans, dayAndYear) }}
另一个具有内联树枝解决方案的解决方案,以及更具可读性的翻译消息文件:
<td>{{ ('month.'~transaction.getDate|date("m"))|trans|raw~' - '~transaction.getDate|date("d - Y") }}</td>
在您的翻译文件中(取决于您设置的配置),例如在 messages.fr.yml 中对于法语翻译,您必须放置这些行:
# messages.fr.yml
month.01: Janvier
month.02: Février
month.03: Mars
month.04: Avril
month.05: Mai
month.06: Juin
month.07: Juillet
month.08: Août
month.09: Septembre
month.10: Octobre
month.11: Novembre
month.12: Décembre
说明:
使用 ~ 运算符将所有操作数转换为字符串并连接它们
使用 |运算符应用过滤器
使用trans函数进行翻译
使用raw来表示日期是安全的(不需要转义html、js...)
请小心括号,因为运算符优先级定义在 http://twig.sensiolabs.org/doc/templates.html
运算符优先级如下,首先列出优先级最低的运算符:b-and、b-xor、b-or、or、and、==、!=、<, >、>=、<=, in, matches, starts with, ends with, .., +, -, ~, *, /, //, %, is, **, |, [], and .:
第一部分括号的解释: ('月。'~transaction.getDate|date("m"))|trans|raw
transaction.getDate|date("m") 首先执行,因为 |运算符比 ~ 运算符具有更高的优先级。 如果 transaction.getDate 的月份是 may,则 transaction.getDate|date("m") 返回 03 字符串 在“月”之后。连接到这个字符串,然后我们就有了month.03
并且因为我们在括号之间设置了 'month.'~transaction.getDate|date("m"),过滤器 trans 仅在字符串 Month.03 被求值后应用...