Share icon

Hey,today we will see how we can create the block type twig template for any specific block type in drupal 8 or drupal 9.

Drupal 8/9 provided a block type option which was not in drupal 7, by the benefit of this you can create you with any specific set of fields and render them according to your wish. but question is how if we need to style the block html in our own way without affecting the any other block type, so our style will only and only apply to block template. so follow the below steps to archive this 

1) First you need to go to URL and here add new "Add custom block type"

2) Add your required fields and save all fields, let say we create the block type "Banner Block"

3) Now go the manage fields and add your fields, like I have added the image field see 

4) Now you need to alter the hook and tell drupal that you want to use the block twig template based on block type, so for that you need to add the code into yourthemename.theme file, just add the following code 

 * Implements hook_theme_suggestions_HOOK_alter() for form templates.
 * @param array $suggestions
 * @param array $variables
function yourthemename_theme_suggestions_block_alter(array &$suggestions, array $variables) {
    if (isset($variables['elements']['content']['#block_content'])) {
      array_splice($suggestions, 1, 0, 'block__bundle__' . $variables['elements']['content']['#block_content']->bundle());

5) Now you need the default block template. so you need to copy that from drupal core block module and you will find in under "/web/core/modules/block/templates", copy and rename the "block.html.twig" to "block--bundle--banner_block.html.twig"

Structure is "block--bundle--machine_name_of_block_type.html.twig"

Now placed that "block--bundle--banner_block.html.twig" in under your theme template folder and clear the cache.

6) Create a new block with block type and placed on any page you want to check

If any issues please comment below to getting help.

Thanks, I hope you found this page Useful, kindly and learn,

Add new comment

Restricted HTML