Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use an image style in a Drupal 8 twig template?

I am trying to print an image using an image style that I've created in my drupal 8 theme.

I can print an image in a template by doing {{ content.banner }} but how do I apply the image style to that image? I tried looking for documentation but there doesn't seem to be any out there.

like image 938
Tyler Marshall Avatar asked Nov 03 '15 22:11

Tyler Marshall


People also ask

How do you apply a Twig image in Drupal 8?

This code worked for me to apply the image style to the field named field_teaser_image: {# set image style #} {% set img = content. field_teaser_image. 0|merge({ '#image_style' : 'thumbnail'}) %} {# render image #} {{ img }} Thanks pavlovich / Megan!

Where can we define a custom image style in Drupal 8?

Go to Configuration > Media > Image styles and define styles as needed.

What are image styles used for in Drupal?

Image styles are used to set presets for image processing. Using image styles, we can crop, desaturate, resize, rotate and scale images. We can also add various effects before an image is displayed. When an image is displayed with a style, a new image file is created and the original image is left unchanged.


1 Answers

Currently drupal 8 doesn't have special filter for applying image style. Instead you can set new attribute for your image like this:

{% set image = image|merge({'#image_style': 'thumbnail'}) %}

Then simply output your updated image:

{{ image }}

P.S . You can do {{ dump(image) }} to see what attributes you can update

like image 75
pavlovich Avatar answered Sep 16 '22 20:09

pavlovich