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

By gdEg6gO1wybjfkUX5h9q, 3 January, 2019

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 }}" />


Plain text

  • No HTML tags allowed.
  • Web page addresses and email addresses turn into links automatically.
  • Lines and paragraphs break automatically.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.