We had a need to set an image as a background element for a <div> tag (see example below). When we tried to the following (with Image as formatter) it only returned the original image url, not the image URL based on the image style.

Without having to use preprocess hooks to modify the URL, we have set the display formatter to be "URL to Image" on the default View Mode and we get the desired results. If I want to use Image formatter, I had to write a preprocess hook, which I want to avoid and adding an additional module like twig_tweak seems over complicating it.

Are there any other alternatives to using the URL to Image formatter and {{ content.field_image.0['#markup] }} without having to use a preprocess hook?

Example using Image formatter

{{ content.field_image.entity.uri.value }}


<div style="background-image: url('/sites/default/files/original-image-url.png')"></div>

Example using "URL to Image" formatter

{{ content.field_image.0['#markup] }}

Results (desired results)

<div style="background-image: url('/sites/default/files/styles/extra-large/public/original-image-url.png')"></div>

Alternative solution

This looks like it will get the url to image with image style.

  1. Set formatter as URL to Image
  2. in twig template use {{ content.field_image.0 }}
  • IMO better to pass the image path in as a variable.
    – Kevin
    Apr 4, 2018 at 18:39
  • That is, from the mytheme.theme file in a preprocess variable.
    – Kevin
    Apr 4, 2018 at 19:43
  • @Kevin In general the mytheme_preprocess_image hook works as you mentioned in mytheme.theme file, but wanted to see of alternatives. Apr 4, 2018 at 21:55
  • @Kevin any thoughts on the alternative solution i just tested and found. Apr 4, 2018 at 22:31

1 Answer 1


Background Image Formatter provides a new formatter that can do this. You will probably want a unique identifier on your target div, but this module should do the trick otherwise. There's a responsive_bg_image_formatter submodule for using responsive image styles for your bg image.

  • @sonfg the mere fact that this also works with Responsive Image module, it resolves multiples scenarios. Apr 5, 2018 at 17:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.