0

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

2 Answers 2

1

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>
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.