Vincent Decaux Vincent Decaux - 6 months ago 87
PHP Question

Twig - Use variable key for object

I am using Twig and I have a problem.

I have a problem when I want to use a variable index for an object.

Here is my code :

{% for label, field in params.fields %}
{{ dump(data.field) }}
{% endfor %}

data is an object containing {'email': '', 'name': 'John'}.

Field is an array of string containing ['email', 'name']

I can't show the value my object dynamicly.

{{ dump( }} works.

How can I use dynamic indexes ? Thanks.


In Twig syntax, data.field is equal to $data['field'] in PHP. In other words, Twig use field as the array key name instead of taking the value of the field variable and use it as a key name.

You can use the attribute() function:

The attribute function can be used to access a "dynamic" attribute of a variable:


{{ dump(attribute(data, field)) }}
{# or simply #}
{{ attribute(data, field) }}