Template suggestions for Drupal 9 block types

Components

By default Drupal 9 doesn't have a template suggestion for block types. If you enable theme debug and inspect a block you'll see something like this:

Image

To fix this and add a suggestion for all block types you have to implement the hook_theme_suggestions_hook() in your *.theme file:

/**
 * Implementation of hook_theme_suggestions_hook().
 */
function MY_THEME_theme_suggestions_block_alter(&$suggestions, $variables) {
  if (isset($variables['elements']['content']['#block_content'])) {
    $bundle = $variables['elements']['content']['#block_content']->bundle();
    array_splice($suggestions, 1, 0, 'block__' . $bundle);
  }
}

If you take a look at theme debug info now you'll see something like this:

Image

As you can see we now have a theme suggestion for the Image block type. Just by implementing one hook, you can now create a different Twig template for each block type.

About the Author

Goran Nikolovski is a web and AI developer with over 10 years of expertise in PHP, Drupal, Python, JavaScript, React, and React Native. He founded this website and enjoys sharing his knowledge.