1

I have four blocks to a view. I want to add class 'fancy-body' to all four blocks. How can I add that.

view_id : categories

display_id's of blocks : block_1, block_2, block_3, block_4

I know, I can add classes by creating individual twig template file for each block. like this,

block--views-block--categories-block-1.html.twig
block--views-block--categories-block-2.html.twig
block--views-block--categories-block-3.html.twig
block--views-block--categories-block-4.html.twig

Is it possible to achieve in single twig template file? How can I achieve that?

Need Help, Thank You!

3
  • What if you add the class to all the block displays in the view manually in Advanced section? Are you going to create a twig file simply to add classes?
    – Akshay
    Nov 26 at 13:11
  • I want to manipulate the structure of all the blocks of a particular view. Nov 26 at 18:24
  • Ok. Then you will need to create a twig file to modify HTML structure. Please modify your question, as it indicates only to add a class.
    – Akshay
    Nov 29 at 5:45
2

If it's just classes you need, the modules mentioned in Joseph's answer should be enough.

If you need to make more alterations and definitely need a custom template file, you can implement hook_theme_suggestions_HOOK().

Something like:

function module_theme_suggestions_block(array $variables) {
  $suggestions = [];

  if ($variables['elements']['#base_plugin_id'] == 'views_block') {
    if (preg_match('/views_block:categories-block_[0-9]+/', $variables['elements']['#plugin_id'])) {
      $suggestions[] = 'block__views_block__categories_all_blocks';
    }
  }

  return $suggestions;
}

With the above example your single template file would be named block--views-block--categories-all-blocks.html.twig.

5
  • what should be the function name, if module name is "XYZ", Is XYZ_theme_suggestions_block() right? Nov 26 at 9:46
  • Yes that's right
    – Clive
    Nov 26 at 9:51
  • the classes and id's that are added in block--views-block--categories-all-blocks.html.twig are reflecting in drupal site. can you tell me where exactly, In what file or In what folder I need to add that code. I added that file in XYZ.module file. thannk you ! Nov 26 at 18:30
  • Is everything should be same or need to be changed? like what is #base_plugin_id and #plugin_id Nov 26 at 18:37
  • You shouldn't need to change anything, it matches the view id and display id from the template files in the question
    – Clive
    Nov 26 at 20:00
2

There are several modules that allow you to add classes to blocks via admin, depending on where you're adding the blocks:

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.