Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drupal 8 - Add machine name to block as class programmatically

I am looking for a way to add a class to a block, but not a custom class, a class from either the region name or the block machine name.

For example, with regions, this is possible:

    {%
       set classes = [ 'region-' ~ region|clean_class]
     %}

And every divs would have the name of the region (defined in the info.yml file) as a class. I want to do the same thing with blocks. Either add the name of the region or the machine name as a class. The reason that I want a class is for CSS. It's better practice to target elements usings classes than IDs.

Does anyone know how to achieve that programmatically?

like image 992
allan00958 Avatar asked May 24 '26 07:05

allan00958


1 Answers

1) Twig on Drupal 8.x understands only variables and basic operations with variables. So in order to use custom variables (such as the block region) you need to pass the variables usually on a preprocess function and then use them inside Twig. Here is an example:

function MYTHEME_preprocess_block(&$variables, $hook) {
  $block_id = $variables['elements']['#id'];
  $block = \Drupal\block\Entity\Block::load($block_id);

  // Add region as variable
  $variables['region'] = $block->getRegion();
}

and then on block.html.twig file:

{%
  set classes = ['region-'~region|clean_class]
%}

See the docs: https://www.drupal.org/docs/8/theming/twig/twig-best-practices-preprocess-functions-and-templates.

2) If you want to have custom block template suggestions (eg for a region) you can alter default theme suggestions using hook_theme_suggestions_alter().

function MYTHEME_theme_suggestions_block_alter(array &$suggestions, array $variables) {
  if ($variables['elements']['#configuration']['region']) {
    $suggestions[] = 'block__' . $variables['elements']['#configuration']['region'];
  }
}

3) Notice that you are not able to use region specific Drupal block twig templates by default because this functionality removed on 8.x. See related post: https://www.drupal.org/node/2011434.

like image 135
TheodorosPloumis Avatar answered May 27 '26 22:05

TheodorosPloumis