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

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 !


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