1

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(&$variables) {

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

  if($node->field_image_de_fond->entity) {
        $image_url = $node->field_image_de_fond->entity->url();
        $css_code = ".header-bg-home { background-image: url('" . $image_url . "'); }";
        $page['#attached']['css'][] = array(
              'data' => $css_code,
              'type' => 'inline',
              'scope' => '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()->attributes->get('node'); in terms of performances.

  • Someone to help with that? – Hugo Oct 7 '15 at 16:13
0

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

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

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.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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