0
votes

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.

1
So obvious. Thank you! If you want, I'd be happy to accept your answer if you create one. - Tienus McVinger

1 Answers

2
votes

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