For my site I want to be able to set custom css variables to the sites head. I don't want to add css files just inline css code. In the end I want users to be able to set colors using a color picker. These colors should be translated to the css variables added to the sites head.
For this I looked at the code in the css vars module this brought me a long way. But i'm not able to add css variables in the body of the page.
For this I use hook_page_top
. But my code now is ending up in the top of the <body>
and I want it to be in the <head>
. Strange enough...when I look at the screencast (min 7:35) of the creator of the css vars module I see that his code does get in to the <head>
.
I simplified the code in my theme_color module to figure out how it works. So maybe that's the problem? How can I get my css variables in the head of the page?
I have a theme_color.module:
<?php
/**
* @file
* CSS Variables module.
*/
use Drupal\theme_color\Hooks;
/**
* Implements hook_page_top().
*/
function theme_color_page_top(array &$page_top) {
Hooks::hookPageTop($page_top);
}
I have a Hooks.php just like the example module:
<?php
namespace Drupal\theme_color;
class Hooks
{
public static function hookPageTop(array &$pageTop)
{
if ($build = self::makeThemeColorBuild()) {
$pageTop['theme_color'] = $build;
}
}
private static function makeThemeColorBuild()
{
$build = [
'#type' => 'html_tag',
'#tag' => 'style',
'#value' => "html:root {\n--test-var: yellow;\n}",
];
return $build;
}
}
Update:
I tried earlier, and again after get the suggestions in comments to use hook_preprocess_html
function theme_color_preprocess_html(&$variables)
{
$build = [
'#tag' => 'style',
'#value' => "html:root {\n--test-var: pink;\n}",
];
$variables['page']['#attached']['html_head'][] = [$build, '?tag?'];
}
This is working but what kind of tag do I need to put after the $build in the $variables line of code??
hook_preprocess_html
as in the accepted answer to the duplicate question.:root { --primary-color: red; }
?hook_preprocess_html
to work but I think I'm missing something. I've edited the original question.