Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twig - Use variable key for object

Tags:

php

twig

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': '[email protected]', 'name': 'John'}.

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

I can't show the value my object dynamically.

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

How can I use dynamic indexes?

like image 785
Vincent Decaux Avatar asked Aug 04 '16 15:08

Vincent Decaux


1 Answers

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) }}
like image 180
A.L Avatar answered Sep 23 '22 20:09

A.L