Use node custom field to choose my posts background I'm building my first Drupal 8 theme and I'd like to add the possibility to change the page background header when editing a post.

I've added a custom field in my post type to provide an image to each post. It works, I can add an image and access the image url on my page.

The problem is that I can't find a way to add inline css to my page to add the background-image property.

Here's my code, located in my .theme file :

function hugo_preprocess_page(&amp;$variables) {

  $node = \Drupal::request()-&gt;attributes-&gt;get('node');

  if($node-&gt;field_image_de_fond-&gt;entity) {
        $image_url = $node-&gt;field_image_de_fond-&gt;entity-&gt;url();
        $css_code = ".header-bg-home { background-image: url('" . $image_url . "'); }";
        $page['#attached']['css'][] = array(
              'data' =&gt; $css_code,
              'type' =&gt; 'inline',
              'scope' =&gt; 'header'
            );
  }

}


Any help would be really appreciated!

As it's my first D8 theme I'm really not sure about the way am doing that, it would probably be better to write a custom css stylesheet with the image url as a parameter, but I've no idea how to do that. Also, I'm not sure about the \Drupal::request()-&gt;attributes-&gt;get('node'); in terms of performances.
Why use a preprocess function ? Instead use a template =).

Here is an example of how I achieve this functionality for the content type "Article" + the image field.

node--article.html.twig

  &lt;header class="main-header post-head " style="background-image: url({{ file_url(node.field_image.entity.fileuri)}})"&gt; &lt;/header&gt;


I added the image on the header on top of my template and use the file_url to get the image from the field_image.

  {{ file_url(node.field_image.entity.fileuri)}}


This will allow you to get the image URL.

Few wrappers + classes to make it this image as background image. And every node will have a custom image background.