Add classes to blocks in a specific region (Updated Version of „Manually loop through blocks in a region.html.twig“)

This is an updated version of this article, because looping through blocks inside a region template is a bad idea, and there are better ways to add classes to blocks.

Solution 1: Add Use Twig suggestions based on the blocks region

If you not only need to add classes to the block (Solution 2), you might want to have separate block template files for each region. This is the closest way to fix the original requirement, to „manually loop through blocks in a region“.

In the meantime, the core adds the Twig suggestions for this, so there is nothing else to do than overriding the block template. For example: block–TECHNICAL-REGION-NAME.html.twig

Solution 2: Using the Block preprocess

To simply add classes or attributes, this may be the preferred way.

https://api.drupal.org/api/drupal/core%21modules%21block%21block.module/function/template_preprocess_block/10

function YOURTHEME_preprocess_block(&$variables) {
  $variables['block_region'] = $block->getRegion();
  // Define block wrappers per region
  if($variables['block_region'] == 'header'){
    $variables['attributes']['class'][] = 'cell';
    $variables['attributes']['class'][] = 'shrink';
  }
}

Solution 3: Using the Fences for Blocks module

You can also archive this manually by using fences for blocks. But if you or someone else forget to add the class, it will rseult in layout issues.

https://www.drupal.org/project/fences_block


Why manually looping blocks in a region template is a bad thing

Blocks are randomly not printed out till you clear the Drupal cache again. What is somehow related to Drupal’s caching system. It simply does not work reliably, that’s why you should modify the blocks itself, in a block preprocess or in the blocks template, like shown above.

    Schreibe einen Kommentar

    Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert


    The reCAPTCHA verification period has expired. Please reload the page.