How to render a block programmatically in drupal 8?

Public
</> CopyGet raw version
php
  1. // You need a block_id! to get it just click configure in the desire block and you'll get url like this /admin/structure/block/manage/bartik_search the last part of the parameter is the block id
  2. $block = \Drupal\block\Entity\Block::load('bartik_search');
  3. $block_content = \Drupal::entityManager()
  4. ->getViewBuilder('block')
  5. ->view($block);
  6.  
  7. return array('#markup' => drupal_render($block_content));

Comments

kienan91's picture

hi ! I used same code for render block. When I update Core 8.1.x => 8.2.x but that code not working .. show error "Recoverable fatal error: Argument 1 passed to Drupal\block\BlockViewBuilder::view() must implement interface Drupal\Core\Entity\EntityInterface" . What's solution to fix ?

Thanks