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?
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) }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With