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
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] }} .
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.
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
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 %}
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