9

我在树枝中显示一个 DateTime 对象,如下所示:

<td>{{ transaction.getDate|date("F - d - Y") }}</td>

现在我希望月份可以翻译,例如April - 20 - 2012应该显示为:Avril - 20 - 2012

我可以这样做吗?如果是这样,怎么做?

我正在研究 Symfony2。

4

3 回答 3

12

或使用国际扩展

{{ "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

并使用 service 激活过滤器:

services:
    twig.extension.intl:
        class: Twig_Extensions_Extension_Intl
        tags:
            - { name: twig.extension }
于 2016-02-25T19:24:38.263 回答
2

另一种具有内联树枝解决方案的解决方案,以及更易读的翻译消息文件:

<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、匹配、开头、结尾、..、+、-、~、*、/、//、%、is、**、|、[] 和 .:

第一部分括号说明:('month.'~transaction.getDate|date("m"))|trans|raw

transaction.getDate|date("m") 首先执行,因为 | 运算符对 ~ 运算符具有更高的优先级。如果transaction.getDate的月份是may,那么transaction.getDate|date("m") return 03 string And after 'month.' 连接到这个字符串,然后我们有month.03

并且因为我们在括号之间设置了 'month.'~transaction.getDate|date("m"),过滤器 trans 仅在字符串 month.03 被评估后应用......

于 2015-04-24T23:34:48.717 回答
2

你可以得到月份部分,然后翻译它:

  {% set month      = transaction.getDate|date('F') %}
  {% set dayAndYear = transaction.getDate|date('d - Y') %}

  {{ '%s - %s'|format(month|trans, dayAndYear) }}
于 2012-04-20T13:55:40.470 回答