I have a twig template for a custom content type. And it is able to render most fields just fine, but I am unable to print an image field with multiple images.

node--mycontenttype.html.twig contains

{{ content.field_mytitle }}
{{ content.field_myheaderimage }}
<div class="row expanded">
    {% for galleryimage in content.field_gallery_images %}
           <div class="gallery-image-item"> {{ galleryimage }} </div>
    {% endfor %}

content.field_mytitle and content._field_myheaderimage outputs the title and image just fine. But when I use the for loop

    {% for galleryimage in content.field_gallery_images %}
           <div class="gallery-image-item"> {{ galleryimage }} </div>
    {% endfor %}

I receive an error

Exception: Object of type Drupal\node\Entity\Node cannot be printed. in Drupal\Core\Template\TwigExtension->escapeFilter() (line 443 of core/lib/Drupal/Core/Template/TwigExtension.php).

When I just use

{{ content.field_gallery_images }}

It's able to output each image, but this does not allow me to wrap each item in divs and add content to each one.

  • 1
    The answer from @4k4 below has many advantages, but for your sanity, replacing: content.field_gallery_images with node.field_gallery_images in your twig 'for' loop would have given you each image entity in the loop. – RominRonin Sep 18 '19 at 8:48

Print the image field in the node template like any other field:

{{ content.field_gallery_images }}

And then use a field twig to loop through multiple field items:


<div class="row expanded">
  {% for item in items %}
    <div class="gallery-image-item">{{ item.content }}</div>
  {% endfor %}

On D8 I was able to make a foreach loop on my images in a way to generate a carousel.

<!-- Wrapper for slides -->
  <div class="carousel-inner" role="listbox">
    {% for i in 0..content.field_accueil_image_slide|length %}
     {%if content.field_accueil_image_slide[i]['#item'].entity.uri.value != "" and content.field_accueil_image_slide[i]['#item'].entity.uri.value is not empty %}
        <div class="item {{ (i == 0) ? 'active' : '' }}" style="">{{ content.field_accueil_image_slide[i]}}</div>
  • Huge help thanks. Why do drupal when you can figure out the rabbit hole in twig? :D – cwiggo Nov 15 '17 at 14:30
  • I this for the node.html.twig? or field.html.twig? – Shakil Ahmad Apr 23 at 15:09
  • @cwiggo, it's not the cleaner way but yes :) – Pauleau Apr 24 at 19:11
  • @ShakilAhmad in this case it is in the node twig because you access to a the content field. But in Drupal you could do this update in multiple ways,.. – Pauleau Apr 24 at 19:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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