Vincent Decaux Vincent Decaux - 3 months ago 41
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': 'test@test.fr', 'name': 'John'}.

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

I can't show the value my object dynamicly.

{{ dump(data.email) }} works.

How can I use dynamic indexes ? Thanks.

A.L A.L
Answer

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:

Example:

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