Is there any hook_preprocess_block or any other way to I can add my custom classes to all blocks of a custom kind?Or in the other words:
How can I target all blocks of custom kind?

For example I want to add search class to all search blocks (or target all search blocks in my theme by using default auto-generated classes by Drupal core if it be available), or add user-login class to all user login blocks and so forth in my theme without any need to create a template for every block.


It's no problem to add classes in a block preprocess hook:

use Drupal\Component\Utility\Html;

  function mytheme_preprocess_block(&$variables) {
    $variables['attributes']['class'][] = Html::getClass('block-id-' . $variables['elements']['#id']);
    $variables['attributes']['class'][] = Html::getClass('block-plugin-' . $variables['elements']['#base_plugin_id']);
    $variables['attributes']['class'][] = Html::getClass('block-provider-' . $variables['elements']['#configuration']['provider']);

This example simply adds the available information to all blocks. You can start with this and narrow it down to what you want.

  • 1
    Thank you so much for your help and attention, I appreciate you very much,This answer is great solution for common blocks targeting in pervasive status, But this method also have a little problem and it seems that it not be very useful for views generated blocks like: Recent content because all blocks of this kind have unique numeric Id like: block-views-block-content-recent-block-1-2 and I can't target all of those blocks effective. Anyway, I thank you very much. – Mojtaba Reyhani Apr 26 '17 at 16:06
  • 1
    In #derivative_plugin_id you'll find [view name]-[display id], the last part of the block id. – 4k4 Apr 26 '17 at 18:06

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.