0

I need to add a style attribute to the .region-content tag in order to set a field-dependent background image.

How do I do this? I have the node in page.html.twig in the page.node variable, but not in region.html.twig, and there doesn't seem to be a way to transfer it from one to the other at that level.

Edit:

This seemed like a good first attempt:

function [THEME]_preprocess_page(&$variables) {
  $variables['page']['content']['#context']['node'] = $variables['node'];
}


function [THEME]_preprocess_region(&$variables) {
  if ($variables['region'] == 'content') {
    var_dump($variables['context']);
  }
}

Unfortunately, that doesn't work - the context variable is still an empty array. How do I transfer context from one theme element to one of its children?

This could be done with a global* variable or something, but that looks horrendously inelegant.

Edit: Well, preferably a call to a function with a static variable, but that still seems like a bad hack.

1 Answer 1

2

In Drupal 8 you can get the node object from the routing system:

function [THEME]_preprocess_region(&$variables) {
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $variables['node'] = $node;
}
1
  • 1
    Works for regions as they are not cached, but be aware that you can't do this for any kind of preprocess without making sure the right cacheability metadata is there. Wouldn't work for blocks for example unless you make sure that the block is cached by URL.
    – Berdir
    Commented Nov 9, 2016 at 19:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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