Drupal 8: How to render your custom theme images with image styles in your Twig template

Posted on: Thu, 01/03/2019 - 07:03 By: admin

In this article we are going to look at how we can render custom images using image styles in your Twig template in Drupal 8. By custom images, I mean images that originate from a custom module/theme (not an image originating from a field entity/node). In other words, the image would not even exist in "public://your-image.png" but rather it might exist somewhere in your custom module or theme.

In YOUR_THEME.theme file, put at the top:

use Drupal\image\Entity\ImageStyle;

Then, depending on which Twig template you want to use the image style, you need to create the appropriate preprocess function. In this example, let's use theme_preprocess_page

So in YOUR_THEME_preprocess_page:

function YOUR_THEME_preprocess_page(array &$variables) {

  $style = ImageStyle::load('custom_style');

  $variables['rounded_image'] = $style->buildUrl(drupal_get_path('theme', 'YOUR_THEME').'/images/your_image.png');

}

Then in your Twig template (for e.g page.html.twig):

<img src = "{{ rounded_image }}" />

 

Tags
English