I want to add some classes to each block that generated in custom region automatically.
For example I want to all blocks that generated within sidebar-left have some special classes and in addition I don't want to those blocks in other regions have those classes.

I try to use something like below code to add desired class to each block that's generated in sidebar-left:


  set classes = [
    'region-' ~ region,
{% if content %}
  <div{{ attributes.addClass(classes) }}>
    {{ content }}
{% endif %}

But it seems there isn't any loop functionality Like below to I can use for each blocks and add my desired classes to them:

{% for item in items %}
  <div class="my-desired-class">
    {{ content }}
{% endif %}
  • 1
    You shouldn't need to - you can target blocks in a region using the region ID.
    – Jaypan
    Apr 15, 2017 at 0:35

1 Answer 1


I am afraid this is no longer possible, according to Region-specific block templates are not available in Drupal 8.

In Drupal 7 it was possible to specify separate block templates per region, such as block--header.tpl.php and block--footer.php to output different HTML for blocks placed in the header and footer regions. It was also possible to adjust variables based on region in hook_preprocess_block(). Both of these features have been removed.

It is suggested you use standard CSS cascading selectors to style blocks differently on different parts of the page.

Therefore, you have 2 options:

1) In your page.html.twig you add a parent/wrapper class or id

{% if page.sidebar %}
    <div class="my-sidebar">
       {{ page.sidebar}}
{% endif %}

Then in CSS use your parent/wrapper to style your blocks .my-sidebar .block { border: solid red; }

2) Individually create a block--block--[id].html.twig for each of your sidebar blocks and add my-desired-class here.

  • Excellent and Comprehensive answer, I appreciate you very much. Apr 15, 2017 at 11:12
  • 2
    I'll have to look into this later when I get back home, but I see no reason why you can't use hook_preprocess_page or hook_preprocess_region, check if there is a block in the region and then add your classes in the preprocess function. Apr 15, 2017 at 14:19
  • @Mark Conroy: Thank you for your attention, I'll be grateful if you post your solution. Apr 16, 2017 at 21:44
  • 1
    @No Sssweat: Please edit your answer and add a space between .my-sidebar and .block It should be like: .my-sidebar .block { border: solid red; }, because div's with block class are descendants of div's with my-sidebar class , Thanks for everything again. Apr 16, 2017 at 21:49
  • If 5 is OK, then 6 also must be ... i.e. I also endorse this answer ... Apr 17, 2017 at 8:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.