In Drupal 8, if you want display blocks on your page, you need to place them in a region.
But in some cases, you don't want place blocks in a region. You would like to place them in an other area, like in a controller callback or node template with preprocess hook.
Today, I will show you how to render a block to anywhere you want.
1. Find the block's plugin_id.
You can find the plugin_id of a block by going to
/admin/structure/block
Then click on any "place block" button and find the block you want to render.
You can see plugin_id = "system_menu_block:main";
Another method to find plugin_id is using Drush
drush ev "print_r(array_keys(\Drupal::service('plugin.manager.block')->getDefinitions()));"
2. Render block with specific configuration.
You already have plugin_id in step 1.
Now you need configuration. With plugin_id you can find which PHP class provide the block by searching by id "system_menu_block".
In PHP class you will see configuration needed.
After you have plugin_id and configuration, you can use snipe code to build render array then render anywhere you want.
$block_plugin_id = 'system_menu_block:main';
$configuration = [
'level' => 1,
'depth' => 1,
'expand_all_items' => FALSE,
'label' => 'Other Products', // Set label of block.
'label_display' => TRUE, // Allow label of block display.
];
$block_plugin_manager = \Drupal::service('plugin.manager.block');
$block_plugin = $block_plugin_manager->createInstance($block_plugin_id, $configuration);
$block_render_array = [
'#theme' => 'block', // Use block template.
'#attributes' => [
'class' => ['book-navigation'] // Add any attributes you want.
],
'#contextual_links' => [
'menu' => [
'route_parameters' => ['menu' => 'main'], // We add a contextual link to quick edit menu.
],
],
'#plugin_id' => $block_plugin->getPluginId(),
'#base_plugin_id' => $block_plugin->getBaseId(),
'#derivative_plugin_id' => $block_plugin->getDerivativeId(),
'#configuration' => $block_plugin->getConfiguration(),
'content' => $block_plugin->build(),
'#id' => NULL,
];
More information:
Add new comment