How to make a Twig date translatable

丶灬走出姿态 提交于 2021-02-07 06:12:38

问题


I am displaying a DateTime object in twig like this:

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

Now I want the month to be translatable, For example April - 20 - 2012 should be displayed as: Avril - 20 - 2012

Can I do this? If so, how?

I am working on Symfony2.


回答1:


or use the The Intl Extension :

{{ "now"|localizeddate('none', 'none', app.request.locale, "Europe/Paris", "cccc d MMMM Y") }}

Will give you something like :

jeudi 25 février 2016

To enable with symfony 2, add to composer :

composer require twig/extensions

And activate filters with service :

services:
    twig.extension.intl:
        class: Twig_Extensions_Extension_Intl
        tags:
            - { name: twig.extension }



回答2:


You can get the month part and then translate it:

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

  {{ '%s - %s'|format(month|trans, dayAndYear) }}



回答3:


A another solution with an inline twig solution, and a more readable translation messages file :

<td>{{ ('month.'~transaction.getDate|date("m"))|trans|raw~' - '~transaction.getDate|date("d - Y") }}</td>

And in your translation file (depends on the configuration you set), for example in messages.fr.yml for a french translation you have to put these lines :

# 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

Explanation :

use of ~ operator to convert all operands into strings and concatenates them
use of | operator to apply a filter
use of trans function to translate
use of raw to indicate the date is safe (no need to escape html, js...)

Careful with parentheses because of the operators priority define in http://twig.sensiolabs.org/doc/templates.html

The operator precedence is as follows, with the lowest-precedence operators listed first: b-and, b-xor, b-or, or, and, ==, !=, <, >, >=, <=, in, matches, starts with, ends with, .., +, -, ~, *, /, //, %, is, **, |, [], and .:

Explanation of the parentheses in the first part : ('month.'~transaction.getDate|date("m"))|trans|raw

transaction.getDate|date("m") is executed first because | operator has a higher priority on ~ operator. If month of transaction.getDate is may, then transaction.getDate|date("m") return 03 string And after 'month.' is concatenate to this string, and then we have month.03

And because we set 'month.'~transaction.getDate|date("m") between parentheses, the filter trans is applied only after the string month.03 was evaluated...



来源:https://stackoverflow.com/questions/10223614/how-to-make-a-twig-date-translatable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!