Manually loop through blocks in a region.html.twig

Update 2: It turns out that the elements array is not reliable available. So i’ve decided to put the .row wrapper in the region.html.twig and add the cell classes per region in the .theme file. This kinda sucks, but i currently see no other way to ensure the cell / column classes are added in a specific region.

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

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.


Update: Don’t use the (old) solution beyond on productive pages. Blocks are randomly not printed out till you clear the drupal cache again. I will do further research on this later.

Since the great ability to modify blocks based on it’s region is gone (https://www.drupal.org/project/drupal/issues/1968360), we were forced to use custom css instead of simple grid system classes to order blocks inside regions.

I don’t want to bloat my CSS code with those repeatative stuff. This is not how grid systems work. If i want to write custom CSS i don’t need a grid system. Sure, we can solve this with SCSS mixins easily, but the result will stay the same: bloated CSS code.

Also we don’t have something like an #items array available that we can cleanly loop through inside a region.html.twig. So we need to use the elements array:

{{ element|render }}

We probably can solve this better inside the .theme file with PHP, but.. i am frontend developer and i rarely use PHP. So i stay with this quick Twig solution.

    Schreibe einen Kommentar

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