Regions for displaying information in twig nodes in Drupal 8

We save a small trick found on the Internet, how to add a custom region that could be displayed in the node template.

Add a function to the .theme of your theme file, or, if there is one, add the necessary code to it

/**
* Implements hook_preprocess_node() for NODE document templates.
*/
function THEME_preprocess_node(&$variables) {
  // Allowed view modes
  $view_mode = $variables['view_mðÊÉíU  ðÊÉíU                  ЛÉÉíU           ™ÉÉíU  XÊÉíU          ÊÉíU   @      ÊÉíU           performance so as to not execute on unneeded nodes)

  // If view mode is in allowed view modes list, pass to THEME_add_regions_to_node()
  if(in_array($view_mode, $allowed_view_modes)) {
    // Allowed regions (for performance so as to not execute for unneeded region)
    $allowed_regions = ['your_node_region'];
    THEME_add_regions_to_node($allowed_regions, $variables);
  }
}

/**
* THEME_add_regions_to_node
*/

function THEME_add_regions_to_node($allowed_regions, &$variables) {
  // Retrieve active theme
  $theme = \Drupal::theme()->getActiveTheme()->getName();

  // Retrieve theme regions
  $available_regions = system_region_list($theme, 'REGIONS_ALL');

  // Validate allowed regions with available regions
  $regions = array_intersect(array_keys($available_regions), $allowed_regions);

  // For each region
  foreach ($regions as $key => $region) {

    // Load region blocks
    $blocks = entity_load_multiple_by_properties('block', array('theme' => $theme, 'region' => $region));

    // Sort ‘em
    uasort($blocks, 'Drupal\block\Entity\Block::sort');

    // Capture viewable blocks and their settings to $build
    $build = array();
    foreach ($blocks as $key => $block) {
      if ($block->access('view')) {
        $build[$key] = entity_view($block, 'block');
      }
    }

    // Add build to region
    $variables[$region] = $build;
  }
}

where instead of THEME we substitute the name of your theme, and instead of your_node_region we add the name of your region for the node.

upd. In case you need to add more than one region, in the line

$allowed_regions = ['your_node_region'];

add names separated by commas

$allowed_regions = ['your_node_region', 'your_node_region_2'];

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
The comment language code.