0

I am trying to create a preprocess function in my .theme file in order to make a variable available to node templates.

I want the variable to contain just the names of all regions that are currently in use (i.e. rendering content).

The idea being, if I have a region called left_hand_nav which is rendered on some (not all) pages, and I have a node called generic_page, from my generic_page node template I'd like to be able to do:

{% if left_hand_nav %}
 do something
{% else %}
 do something else
{% endif %}

I am not interested in controlling the rendering of any regions blocks from the node template. Instead for any given page wherein the node is rendered I just want to know if a particular region on said page is in use.

I realize this can very easily be done from a page template but instead of having a kazillion billion conditionals in my page template I'd prefer a few conditionals in several node templates.

If someone could point me in the right direction I'd appreciate it very much.

3
  • 1
    Are you talking about whether regions in your page.html.twig template have content, i.e. the regions defined in your theme's .info.yml file?
    – sonfd
    Sep 1 at 15:41
  • @sonfd yes but I want to know from within node templates. Sep 1 at 15:43
  • 2
    I can see the motivation for this from a frontend dev point of view, but Drupal's architecture (entity caching, BigPipe,...) makes this extremely hard to work even halfway reliable. I fear there is no right way for this.
    – Hudri
    Sep 2 at 8:33
1

In special case of navigating to a node page (like when viewing an article) you can see that when implementing hook_preprocess_page , the $variables does contain a 'node' value, if you add any property to your $variables['node'] , you will be able to use it in node.html.twig file

Update

As in hook_preprocess_page you can access all regions using $variables['REGION_NAME'] , so that you can check them if they are empty or having content , if they weren't empty you can save their name in an array and then apply that array to $variables['node']

2
  • 2
    You can't set properties in $variables['node']. The node object is statically cached and all variables referencing this object share the same instance. Also page and node are processed and cached independently from each other and you don't know which one is processed first. Most times they are not even processed in the same request because page and node are stored in different cache bin/keys and with different cache metadata.
    – 4k4
    Sep 2 at 9:26
  • Thank you @4k4 that explains why it wasn't working. Sep 2 at 13:47

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.