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.

Mafii
  • 7,227
  • 1
  • 35
  • 55
Tyler Marshall
  • 314
  • 2
  • 5
  • 15

4 Answers4

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

Megan
  • 103
  • 3
pavlovich
  • 1,935
  • 15
  • 20
  • 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. – Tyler Marshall Nov 17 '15 at 06:36
  • 2
    What variable should I use for "image" ? content.field_bloc_1_image.entity does not works for example :s – Paul Leclerc Jan 30 '17 at 11:34
  • 1
    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 }} – paul cappucci Sep 22 '17 at 11:10
  • 1
    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! – Pagri Apr 24 '18 at 16:40
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 !

Kevin Wenger
  • 1,484
  • 1
  • 13
  • 29
  • 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->..` – ARUN Aug 23 '17 at 05:18
  • 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: https://www.drupal.org/docs/8/modules/bamboo-twig/usage. The functions are `bamboo_render_image` & `bamboo_render_image_style`. – Kevin Wenger Aug 23 '17 at 05:41
  • 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? – user3321095 Oct 11 '21 at 19:58
3

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 %}
Stef Van Looveren
  • 302
  • 1
  • 5
  • 15
0

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.

Dalin
  • 3,012
  • 1
  • 21
  • 21