I have created a variable to use in my twig template. The variable consists of a nested array. If I dump the variable I get the following result:

array (size=2)
  'img' => 
    array (size=15)
      0 => 'path-to-file.jpeg'
      1 => 'path-to-file.jpeg'
   'alt' =>
    array (size=15)
      0 => 'img 1 alt text'
      1 => 'img 2 alt text'

I want to loop through gallery_images and map the alt text to the image. My loop was working fine before I added the nested array / alt text. This is how I expected it to work:

{% for gallery_image in gallery_images %}
      <img src="{{ gallery_image.img }}" alt="{{ gallery_image.alt }}" />
{% endfor %}

That did not work, then I tried to call the src and alt with

{{ gallery_image.0 }}
{{ gallery_image.1 }}

Then I only got 1 file and 1 alt text. What is the correct way to loop through the nested array? Also bear in mind I may want to add title text next.

1 Answer 1


Do you have control over your array structure?

Why not just change it to this:

  0 => ['alt' => 'alt text', 'img' => 'image-path'],
  1 => ...?

Because then your logic would work, but right now you have the reversed structure. What you could do is loop over the image paths with {% for key, path in gallery_images.img %} and use the key toaccess gallery_iamges.alt[key]` (not 100% sure about the exact syntax). Certainly more complicated that way.

  • Yes I do have control because I am creating the array in the .theme file, so I will try that. Thanks. Sep 22, 2017 at 9:20

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.