Reputation: 9990
Is it possible to get the key of an array in Twig (in Symfony)?
For example if I have an array of:
array(
'key1' => 'value1',
'key2' => 'value2',
);
Is it possible in Twig to print:
key1: value1
key2: value2
Thanks
Upvotes: 28
Views: 55439
Reputation: 10717
Try following format:
{% for key, value in array %}
{{ key }} - {{ value }}
{% endfor %}
More Information on Offical Twig about Iterating over Keys and Values
https://twig.symfony.com/doc/3.x/tags/for.html#iterating-over-keys-and-values
Upvotes: 50
Reputation: 210
If you have this array: person = ['name': 'John', 'age': '30']
, you can display the value of a specific key, like this:
<p> Name = {{ person.name}} </p>
<p> Age= {{ person.age}} </p>
Upvotes: -1
Reputation: 1482
You can use the keys filter. The keys filter returns the keys of an array.
{% set keys = array|keys %}
or
{% for key in array|keys %}
{{ key }}
{% endfor %}
Upvotes: 26