Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing array values using array key from Twig

Tags:

php

twig

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

like image 529
Joseph Woodward Avatar asked Nov 09 '11 00:11

Joseph Woodward


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 access array keys?

Array elements can be accessed using the array[key] syntax. ); var_dump($array["foo"]); var_dump($array[42]);

Can array key be an array?

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.

How do you find the key and value of an array?

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.


1 Answers

Have you just tried this:

attribute(item2, key).title
like image 64
Guillaume Poussel Avatar answered Oct 08 '22 21:10

Guillaume Poussel