Template suggestions for Drupal 9 block types


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:


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:


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 senior web developer who loves working with Drupal, React, and React Native. He is the founder of this website and he enjoys sharing his knowledge. Need help with anything? Get in touch.