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),
];