2

How do I render a custom block type (block_content) programmatically with a specific display view?

4

In hook_preprocess_page() add the following code.

$block_entity = Drupal\block_content\Entity\BlockContent::load(BLOCK_ID);// BLOCK_ID
$block_view = \Drupal::entityTypeManager()->getViewBuilder('block_content')->view($block_entity, 'DISPLAY_VIEW_NAME');
if ($block_view) {
    $variables['page']['my_block'] = $block_view;
}

In your Twig template, print the block with the following code.

{% if page.my_block %}
  {{ page.my_block }}
{% endif %}
| improve this answer | |
  • How to know what is block id and DISPLAY_VIEW_NAME in views in drupal 8? – Amit Kumar Dec 28 '16 at 9:40
3

If your block is custom, this worked for me:

$customblock = \Drupal::service('plugin.manager.block')->createInstance('{id of block here}', []);

Then you could print it from your preprocess like so:

if(isset($customblock) && !empty($customblock)) {
  $variables['logo'] = $customblock->build();
}

When you created your block, you would have set the ID here:

/**
  * Provides a 'Logo' Block.
  *
  * @Block(
  *   id = "logo",
  *   admin_label = @Translation("Logo"),
  *   category = @Translation("Header"),
  * )
  */

However, this method stops contextual links from displaying. To work around this you can do the following:

$Block = \Drupal\block\Entity\Block::load($id);
if(isset($Block) && !empty($Block)) {
  $Block =  \Drupal::entityTypeManager()->getViewBuilder('block')->view($Block);
}

Please note: the block needs to be placed in a region in the block layout page (but can be set to Disabled) and the $id is equal to the instance of that block, NOT what you defined in the .php file. This can be found by hovering on any of the block links in block layout.

| improve this answer | |
0

If you've created the block as a View you can use views_embed_view in your template_preprocess_page function, something like:

$variables['my_block'] = views_embed_view('view_machine_name', 'block_machine_name');

Sub in the View and block machine names. View name visible at admin/structure/views and the block machine name on the specific block's Advanced settings (defaults to 'block_1').

| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.