How to change background image based on current node? I am trying to change the header background image of my website based on the current node. I have added an image field to my content type, field_hero_image, and, in preprocess function mytheme_preprocess_page(&amp;$variables), I get the image url and try to inject it in the page, as inline css:

function mytheme_preprocess_page(&amp;$variables) {

    $node = $variables['node'];
    if ($node) {
           $path = file_create_url($node-&gt;field_hero_image-&gt;entity-&gt;getFileUri());
            $variables['page']['#attached']['css'] = array(
                'data' =&gt; '.header-wrapper { background:url(' . $path . ') center center no-repeat !important; background-size: cover;}',
                'type' =&gt; 'inline',
            );
    }
}


or

function mytheme_preprocess_page(&amp;$variables) {

    $node = $variables['node'];
    if ($node) {
           $path = file_create_url($node-&gt;field_hero_image-&gt;entity-&gt;getFileUri());
           $variables['#attached']['library'][] = array(
            'data' =&gt; '.header-wrapper { background:url(' . $path . ') center center no-repeat !important; background-size: cover;}',
            'type' =&gt; 'inline',
        );
    }
}


None of this works.

Is there a way to inject css from the preprocess function? I know that I can get the path value, put it in $variables and use it in twig. But this doesn't seem a clean solution to me.
You can make a different templete and use, for example, a class and load the different img by css is one of many possible soluctions, I think that is the best practice

You can read more about Drupal 8 Temple in these threads:

https://www.drupal.org/docs/8/theming

https://www.drupal.org/docs/8/theming/twig

Example aplications 

function YOURTHEMENAME_preprocess_node(&amp;$variables) {
  if ($variables['node']) {
    $node = $variables['node'];
    switch ( $node-&gt;nid ) {
    case 'nid1':  // Replace nid1 etc with your nid
    case 'nid2':
      break;
    }
  }
}


Template/node/node--full--[nid]

    &lt;div class="img--hero--image"&gt;
    &lt;/div&gt;


Other solutions it is use a field in the content type and use this field to render in your background.