Skip to main content
Image
Drupal Sapiens snippet

How to display a block programmatically

In this snippet I show the different ways to display a block through code.

Content blocks: these are blocks that you create from the Drupal interface, for example.
$bid = 20 // Get the block id through config, SQL or some other means.
$block = \Drupal\block_content\Entity\BlockContent::load($bid); // Load block entity.
$render = \Drupal::entityTypeManager()->
  getViewBuilder('block_content')->view($block);
return $render;
Plugin blocks: these are blocks that have been defined as plugins through some module. An example would be the language switcher block.
$block_manager = \Drupal::service('plugin.manager.block'); // Get block manager service.
// Get the same settings from this block.
$plugin_block = $block_manager->createInstance($block->getPluginId(), $block->get('settings'));
$render = $plugin_block->render(); // Render plugin block.

return [
  '#markup' => render($render),
];
Etiquetas

Join the Drupal Sapiens Community

Save content that interests you, connect with others in the community, contribute to win prizes and much more.

Login or create an account here

Featured

Last news