Does anyone know how (of if it's even possible!) to do this in Twig? I can't see anything in the documentation as to whether it's possible.
The PHP array is structured as below:
$data['data']['a']['title'] = 'Title 1';
$data['data']['a']['title'] = 'Title 2';
$data['data']['b']['title'] = 'Title 3';
Twig template code below:
{% for letter in 'a'..'z' %}
{{ letter }}
<ul>
{% for key, item1 in data %}
{% for item2 in item1 %}
<li>{{ item2[key].title }}</li>
{% endfor %}
{% endfor %}
</ul>
{% endfor %}
Edit: After further investigation, it appears the attribute (see http://twig.sensiolabs.org/doc/functions/attribute.html) function should do the job but I am unsure as to how to use it in these circumstances.
Many 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] }} .
Array elements can be accessed using the array[key] syntax. ); var_dump($array["foo"]); var_dump($array[42]);
As array values can be other arrays, trees and multidimensional arrays are also possible. And : The key can either be an integer or a string.
The array_keys() function is used to get all the keys or a subset of the keys of an array. Note: If the optional search_key_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the array are returned.
Have you just tried this:
attribute(item2, key).title
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