3

Is it possible to add inline CSS to into the <head> section of a Drupal 8 page? My expected result should look like this:

<head>
<style>
.my-custom-class {
  background-color: red;
}
</style>
</head>

I've tried to add it to hook_preprocess_HOOK() but it will not show up.

function my_module_preprocess_html(&$variables) {
  $variables['html']['#attached']['css'][] = array(
    'type' => 'inline',
    'every_page' => TRUE,
    'data' => '.my-custom-class { background: ' . $dynamic_color . '; }',
  );
}

I've tried a few other things but it did not work either. Whats the right way to do this?

7

After doing some more research i've found an answer to my problem. The main reason for not finding a solution was, they don't want you to do this in Drupal 8.

From their documentation:

https://www.drupal.org/developing/api/8/assets#dynamic-css-js

If the dynamic CSS/JS is built for each request, then you enter the truly advanced territory. This is hard, and for a good reason: per-request dynamic assets have to be built on every single request and therefore slow Drupal down. We want to make it hard to make Drupal slow down, so this is why we don't offer a nice API for this — since we don't want you to do it.

This makes sense and there is a short description how to get it to work anyway but its lacking of an example. This is what i've done to get it to work:

function my_module_page_attachments_alter(array &$page) {
  $background_color = '#000';
  $page['#attached']['html_head'][] = [
    [
      '#tag' => 'style',
      '#value' => '.my-custom-class { background: ' . $background_color . '; }',
    ],
    'my-custom-module'
  ];
}
  • Thanks. I have successfully applied this method in a hook_ENTITY_TYPE_view_alter implementation. It works great and the result seems to be cached as you would expect: the logic of adding the CSS is executed only once per entity (until you clear your cache of course). – marcvangend May 1 '18 at 12:18
  • By the way, a downside of this approach is that you cannot control where it ends up in the HTML head. The Classy theme will place it before normal CSS files. – marcvangend May 1 '18 at 15:01

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.