简体   繁体   中英

Render nested associative array with twig

I'm facing a little problem that I need help with. I've got this php application which passes data to a twig html template.

My PHP Code generates the following (simplified):

$menuItemsWithPictures = array(
   'PageName' => "page_name",
   'pictures' => array('/path/to/picture1.jpg', '/path/to/picture2.jpg'),
);

In my frontend I would like to have each of the items in the $menuItemsWithPictures rendered into something like this (again, very simplified here):

<div>
  <a href=PageName><!-- Taken from the PageName key in the array-->
     <img src=picture1 /> <!-- taken from pictures array [0] -->
     <img src=picture2 /> <!-- taken from pictures array [1] -->
  </a>
</div>

I tried some variations of {% for key, value in array %} , to no avail though, because I alway ended up with the a tag being generated as often as the array is long.

Could someone point me in the right direction here, perhaps?

Greetings, derelektrischemoench

I think you got the array example a bit wrong. I believe you are actually going for a multidimensional array, aren't you? Like this:

$menuItemsWithPictures = [
    [
        'pageName' => 'page_name',
        'pictures' => array('/path/to/picture1.jpg', '/path/to/picture2.jpg'),
    ],
    [
        'pageName' => 'another_page',
        'pictures' => array('/path/to/picture1.jpg', '/path/to/picture2.jpg'),
    ]
];

If this is the case, then the corret Twig syntax would be:

<div>
    {% for item in menuItemsWithPictures %}
        <a href="{{ item.pageName }}">
            {% for image in item.pictures %}
                <img src="{{ image }}"/>
            {% endfor }
        </a>
    {% endfor %}
</div>

You will need a nested loop to achieve what you want, the first loop will iterate through the pages and the inner loop will handle the pictures:

<div>
{% for page in pages %}
  <a href="#{{ page.PageName }}">
  {% for picture in page.pictures %}
     <img src={{ picture }} />
  {% endfor %}
</a>
{% endfor %}
</div>

Here is a twig fiddle for your use case: https://twigfiddle.com/8ncmqi

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM