Nov 08, 2019 in Drupal 8, Snippets

I had to loop over some images in Twig and dynamically adding image styles to them. Without using contrib this seemed a bit hard to do. I found a fix and I share it here with you. The trick is to make it a new render array, and to add your values to it. 

  {% for item in content.field_images['#items'] %}
    {% set image = {
      '#theme':      'image_style',
      '#style_name': 'medium',
      '#uri':        item.entity.uri.value,
      '#alt':        item.alt,
      '#width':      item.width,
      '#height':     item.height
    } %}
    {{ image }}
  {% endfor %}