Programatically display a block on a page template

Problem:

I need to place a block added by another module on my page. I cannot add it by placing the block on a region. Because there is specific placement on the content region itself

Solution:

Add the block programatically to the page. We can get the block content programatically on a hook_preprocess function and add it to the $variables to print on the twig template

/**
 * Implements hook_preprocess_HOOK() for Block templates.
 * Ex: YOUR_THEME_preprocess_page()
 */
function YOUR_THEME_preprocess_HOOK(&$variables) {
$block_manager = \Drupal::service('plugin.manager.block');
// You can hard code configuration or you load from settings.
$config = [];
//Get the breadcrumb block
$plugin_block = $block_manager->createInstance('system_breadcrumb_block', $config);
// Some blocks might implement access check.
$access_result = $plugin_block->access(\Drupal::currentUser());
// Return empty render array if user doesn't have access.
// $access_result can be boolean or an AccessResult class
if (is_object($access_result) && $access_result->isForbidden() || is_bool($access_result) && !$access_result) {
  // You might need to add some cache tags/contexts.
  return [];
}
$block_content = $plugin_block->build();
// In some cases, you need to add the cache tags/context depending on
// the block implementation. As it's possible to add the cache tags and
// contexts in the render method and in ::getCacheTags and
// ::getCacheContexts methods.

$variables['breadcrumb'] = $block_content;

}

 

// Then on the TWIG template you just print it like below anywhere you want
// example on the page.html.twig

{{ breadcrumb }}

Thats it.