I followed steps given in this link to create a custom Page.
Page is created and 'Hello world' is printing in the page, now i want to render some blocks in that page. How can I achieve this task?
Drupal Answers is a question and answer site for Drupal developers and administrators. It only takes a minute to sign up.Sign up to join this community
Given that you're using a custom controller for your page, you have the option to load the block from your controller, or place the block in another region outside of that part of the page that the Controller controls.
For blocks such as global elements such as headers and footers, I would recommend you place them through the CMS at /admin/structure/block
For blocks that sit above or below the content that your controller loads, you can also place them from /admin/structure/block or you can load them from within the the controller.
If you need to place content above and below your block, you'd probably want to load it programmatically in your controller.
Here's a guide on loading blocks programmatically.
basically in your myPage() method that is returning the build array, you'd want the build array for the block you want to load.
$build['events'] = \Drupal::service('plugin.manager.block') ->createInstance('my_events_block') ->build(); $build['recent_insights'] = \Drupal::service('plugin.manager.block') ->createInstance('recent_articles', ['title' => 'Some Recent Articles', 'offset' => 0]) ->build(); return $build;
The code above works for the types of blocks that you custom create in your module, such as at /mymodule/src/Plugin/Block/RecentArticles.php
It doesn't work for loading an instance of a block that was created through the CMS.
For those you need to use:
$block = \Drupal::entityTypeManager()->getStorage('block')->load('myblock'); $build['myblock'] = \Drupal::entityTypeManager()->getViewBuilder('block')->view($block);
To render block on your custom page, go to Structure, then Block Layout, from there you can either create a custom new block (enable Custom Block for that), or configure the existing block. To place on your page, in Configure page, go to Pages under Visibility section and add path of your custom page to the list, then save. Your block should be shown according to assigned region.
If your custom page uses Twig template, see: How to render a template in Drupal 8.
If you'd like to create your own block programatically, see: Block API overview.