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(&$variables)
, I get the image url and try to inject it in the page, as inline css:
function mytheme_preprocess_page(&$variables) {
$node = $variables['node'];
if ($node) {
$path = file_create_url($node->field_hero_image->entity->getFileUri());
$variables['page']['#attached']['css'] = array(
'data' => '.header-wrapper { background:url(' . $path . ') center center no-repeat !important; background-size: cover;}',
'type' => 'inline',
);
}
}
or
function mytheme_preprocess_page(&$variables) {
$node = $variables['node'];
if ($node) {
$path = file_create_url($node->field_hero_image->entity->getFileUri());
$variables['#attached']['library'][] = array(
'data' => '.header-wrapper { background:url(' . $path . ') center center no-repeat !important; background-size: cover;}',
'type' => '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.
z-index
property, ie:z-index: -10;
page.htm.twig
file, with image url coming from a variable. I was just looking for the "right way" to do the thing.