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

4

12

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.

Centiare answered 3/11, 2015 at 22:10 Comment(0)
L
13

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

Lodmilla answered 12/11, 2015 at 10:56 Comment(4)
I also actually found in the content type settings, you can display all images for that content type to be of Image Style X. So I could do it from my answer or yours, but yours is better imo.Centiare
What variable should I use for "image" ? content.field_bloc_1_image.entity does not works for example :sExtranuclear
I could not get this to work. It does not use the image style? I have {% set image = content.field_global_image|merge({'#image_style': 'thumbnail'}) %} {{ image }}Gyimah
I am using a media bundle for my image and rendering it in a node display of teaser. 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!Zuckerman
P
5

I resolve this by creating my own Twig Filter.

You can do the same by creating your own module exposing this Filter.

Feel free to re-use it.

Code

namespace Drupal\twig_extender\TwigExtension;

use Drupal\node\Entity\Node;
use Drupal\Core\Link;
use Drupal\Core\Url;

use Drupal\file\Entity\File;
use Drupal\image\Entity\ImageStyle;

class Images extends \Twig_Extension {
     /**
     * Generates a list of all Twig functions that this extension defines.
     */
     public function getFunctions(){
         return array(
             new \Twig_SimpleFunction('image_style', array($this, 'imageStyle'), array('is_safe' => array('html'))),
         );
     }

    /**
    * Gets a unique identifier for this Twig extension.
    */
    public function getName() {
        return 'twig_extender.twig.images';
    }


     /**
      * Generate images styles for given image
      */
      public static function imageStyle($file_id, $styles) {
          $file = File::load($file_id);
          $transform = array();
          if (isset($file->uri->value)) {
              $transform['source'] = $file->url();
              foreach ($styles as $style) {
                  $transform[$style] = ImageStyle::load($style)->buildUrl($file->uri->value);
              }
          }
         return $transform;
      }
}

Usage

{% set transform = image_style(image.entity.fid.value, ['thumbnail', 'large']) %}

Then you have access to the source image & styles

{{ transform.source }}
{{ transform.thumbnail }}
{{ transform.large }}

Hope it will help you guy !

Poulterer answered 28/7, 2016 at 8:23 Comment(3)
I tried above method. I put the above code in /modules/custom_module/src/TwigExtension/Images.php But still getting error Twig_Error_Syntax: Unknown "image_style" function. in Twig_ExpressionParser->..Patronage
From now I'm using Bamboo Twig (Drupal 8 module). Which expose, in the Bamboo Twig Loader extension, 2 twig functions to render images. Here the doc of Bamboo Twig: drupal.org/docs/8/modules/bamboo-twig/usage. The functions are bamboo_render_image & bamboo_render_image_style.Poulterer
One of our Drupal projects is using this code snippet. It throws an error after upgrading to Drupal 9. "Call to a member function buildUri() on null". Anyone run into this?Succedaneum
B
4

How to do this without contrib module: make it your own render array.

{% 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 %}
Barcus answered 8/11, 2019 at 14:19 Comment(0)
E
-1

It's probably worth mentioning, that it's useful to first question your assumption. Do you really need to do this in Twig? If you can just configure a view-mode (or Views field) to render the image field with the appropriate (responsive) image style, that would be much simpler.

Emilia answered 21/3, 2019 at 14:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.