Tienus McVinger
Tienus McVinger

Reputation: 477

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.

Upvotes: 0

Views: 557

Answers (1)

DarkBee
DarkBee

Reputation: 15634

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

Upvotes: 2

Related Questions