How to get a Drupal image style URL from a media field in a twig template


There’s plenty of information on how to render a raw field value in a twig template, how to obtain the url form an image - even from a media field. The image style url from a media field however, can be quite tricky. Here’s how to do it.

Published on August 25, 2020

When migrating our Drupal website from 7 to 8, after much debate, we decided to convert all image fields on our old website to media fields in our Drupal 8 website. Little that we realise that we would eventually run into a little theming difficulty along the way. What seemed like a very basic requirement at first glance, turned out to be a little harder than we thought.

The hero images used in this website are in fact images from a media field on content type ‘article’. In Drupal 7, we would have used an image field and programmatically get the image url in a node template, like so:

  $hero_img = file_load($node->field_image['und'][0]['fid']);
  $hero_uri = $hero_img->uri;
  $hero_url = image_style_url("my_image_style", $hero_uri);

And set it as a background image like this:

<div style="background-image: url('
  <?php print $hero_url ?>

Yes, there probably is a module for that, but where’s the fun in that, right?

Retrieving the image url from an image field in Drupal 8 and 9 seemed pretty straightforward too. Even the solution for getting the image style url from a simple image field can be found quite easily. Getting the image url from a media field can also be looked up easily. 

For some reason however, it seemed nobody had attempted to retrieve the image style url from a media field image in Twig before. Or at least nobody had documented how to do it. There’s a twig module called Twig Tweak, but it doesn’t appear to support image styles. 

Finally, after lots of Googling, documentation skimming and trial and error, we found the solution. This is what we ended up using in our twig node template:

<div style="background-image: url('
  {{ node.field_media_image|file_url }}

This will respect the image style set in your Drupal admin. The image style is set in on the Manage Display tab of your content type. 

That's it folks! Hope this helps anyone out there.


Need help developing your Drupal website? Our team of expert Drupal developers would be more than happy to help you out!


planet drupal
drupal 8
drupal 9