简体   繁体   中英

translation strings in twig inside an object

I'm trying to put translation strings inside an object within Twig. So far I haven't got it right and can't figure out how to properly do it. I didn't think this would work, but it was my best effort so far.

{% set options = {
    0 : {{ 'user.first_name'|trans }},
    1 : {{ 'user.surname'|trans }},
    2 : {{ 'user.initials'|trans }}
} %}

I get the error:

A hash key must be a quoted string, a number, a name, or an expression enclosed in parentheses (unexpected token "punctuation" of value "{".

Any one any ideas? Thanks in advance.

The syntax {{ ... }} is used to output content. You don't need to interpolate the variable in order to add it to the object

{% set options = {
    0 : user.first_name|trans,
    1 : user.surname|trans,
    2 : user.initials|trans,
} %}

Some extra notes. As you are using numeric indices you could use the following snippet

{% set options = [
    user.first_name|trans,
    user.surname|trans,
    user.initials|trans,
] %}

demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM