How to use Media Entity asset as a background image

So, I have been using the new Media Entity module, along with some of the other media modules on some websites, and generally I like it. I find it awesome to be able to create different Entity Browsers, based on tagging, so if I'm adding hero images to my Hero Image block, my entity browser can have a special view.

In order to use the Hero image from my block as a background image, I had to Google a little. Hence my post, I wanted to document what I did, if for nothing else, my own reference. So here we go.

First we have to write a template hook, in order to access the data:

function THEMENAME_preprocess_block(&$variables) {
  if($variables['attributes']['id'] == 'BLOCK_MACHINE_NAME') {
    $image_obj = $variables['content']['field_FIELD_NAME'][0]['#media'];

    if (!empty($image_obj)) {
      $variables['hero_image'] = \Drupal\image\Entity\ImageStyle::load('IMAGE_STYLE_MACHINE_NAME')->buildUrl($image_obj->field_FIELD_NAME->entity->getFileUri());

So, as you might notice, capitalized words are the one you would be replacing for your own.

In my block--BLOCK_MACHINE_NAME.html.twig file, I then can access the path to the file like this:

<section class="frontpage-hero" style="background-image: url('{{ hero_image }}');">

Very simple, just like everything else ... as soon as you realize it :D


Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.