This project is not covered by Drupal’s security advisory policy.

This module aims to make it easier to render blocks programatically in Drupal 8.

If you wish to render a block programatically, you already need a Block Entity instance in the block layout to be able to render it elsewhere. This means that you would need to hide your instances in some region, never to be printed or instantly disable them after creating, just so you could render them elsewhere in your code.

Another option would be to render the Block Plugins themselves. But by bypassing the Block Entities, your output won't be put through a theming function and therefore you lose the wrapper DIV for theming and contextual links also won't be rendered.

This module tries to solve this by implementing a theming function of its own based on the block twig template. This way we don't need to have any Block Entity instances in the block layout and can still get a wrapper DIV, including contextual links related to the block.

To use this, you need to call the block_renderer service and use the appropriate function to render your block.

$blockRenderer = \Drupal::service('block_renderer');
// Pass the ID of the block plugin you wish to render.
$plugin_block = $blockRenderer->renderPluginBlock(‘plugin.id');
return $plugin_block;

A separate function has been made to render Block Content entities, so you'd be able to just pass the Block Content ID instead of its more complicated UUID that would be needed when trying to render it by using the corresponding Block Plugin.

$blockRenderer = \Drupal::service('block_renderer');
// Pass the ID of the block content you wish to render.
$content_block = $blockRenderer->renderContentBlock(‘content.id');
return $content_block;

If you wish to provide your own attributes (HTML classes), you can provide a config array with those values.

$blockRenderer = \Drupal::service('block_renderer');

$config = [
  '#attributes' => [
    'class' => ['block-info'],
  ],
];
// Pass the ID of the block content you wish to render + additional config.
$content_block = $blockRenderer->renderContentBlock(‘content.id', $config);
return $content_block;
Supporting organizations: 
Sponsoring

Project information

Releases