Twig templates for custom block types in Drupal

 

Similar to content types, Drupal offers the ability to create custom block types. Here’s how to enable custom Twig templates for each of your custom block types.

Published on March 10, 2023

By default, a standard Drupal installation already comes with a predefined block type that is used when you add a custom block to a region: the Basic block. It only has a title and body field. Drupal block types work quite similar to content types. It allows you to create a particular type of block by adding and managing fields, form display and display modes.

Out of the box, Drupal offers several ways to use a Twig template to theme your custom block. However, when you want to create a Twig template that applies to all blocks of a specific block type, you need a few lines of code.

To enable templates for custom block types, we use theme suggestions. Assuming you have a custom Drupal theme called "mycustomtheme", place the following snippet in your mycustomtheme.theme file:

function mycustomtheme_theme_suggestions_block_alter(array &$suggestions, array $variables) 
{ 
  // Block suggestions for custom block types. 
  if (isset($variables['elements']['content']['#block_content'])) { 
    array_splice($suggestions, 1, 0, 'block__type__' . $variables['elements']['content']['#block_content']->bundle()); 
  } 
}

Now you can use block–type–my-block-type.html.twig to theme every custom block of the block type you have created.

Happy theming!

drupal
development
theming
twig
planet drupal