b85411
b85411

Reputation: 9990

Getting array keys in Twig? (Symfony)

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

Answers (3)

Bora
Bora

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

Hamid ER-REMLI
Hamid ER-REMLI

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

Pethical
Pethical

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

Related Questions