Drupal - Rendering an image field in page.html.twig with a custom image style

Replace the image tag

<img class="swiper-image" src="{{ file_url(node.field_slides[key].entity.uri.value) }}" alt="{{ node.field_slides[key].alt  }}" />

with a render array for the image style:

{% set imagestyle = {
  '#theme':      'image_style',
  '#style_name': 'medium',
  '#uri':        node.field_slides[key].entity.uri.value,
  '#alt':        node.field_slides[key].alt,
  '#attributes': { class: 'swiper-image' },
} %}

{{ imagestyle }}

Edit:

There is a new filter in the module Twig Tweak. Now you can generate the image style url in twig directly from an uri or url:

{{ node.field_slides[key].entity.uri.value | image_style('thumbnail') }} 

Just an update for the 4k4 answer.

To print entity fields (eg. paragraph), we can use this:

<img src="{{ item.entity.field_image.entity.uri.value | image_style('image_style') }}" alt="{{item.entity.field_image.alt}}"/>


To print a responsive image style:

{% set responsiveimagestyle = {
    '#theme': 'responsive_image',
    '#responsive_image_style_id': 'responsive_image_style',
    '#uri': node.field_slides[key].entity.uri.value,
    '#attributes': { class: 'swiper-image', alt: 'text', title: 'text' },
} %}

{{ responsiveimagestyle }}

Tags:

Media

Theming

8