Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 925
b85411 Avatar asked Jul 01 '14 05:07

b85411


People also ask

How do you access an array in Twig?

Accessing array elements Twig as a parameter can receive array. To access a specific element of array you can use regular php array access bracket notation {{ array[key] }} .

How do you dump in Twig?

In a Twig template, you can use the dump utility as a function or a tag: {% dump foo. bar %} is the way to go when the original template output shall not be modified: variables are not dumped inline, but in the web debug toolbar; on the contrary, {{ dump(foo.


2 Answers

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

like image 76
Bora Avatar answered Oct 18 '22 20:10

Bora


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 %}
like image 34
Pethical Avatar answered Oct 18 '22 19:10

Pethical