We're migrating some code to D8 and in some of our nodes' body field we used to call PHP code directly with the now defunct module_invoke to render a block in the node before the content.

All the examples I can find explain how to do that in D8 with themes or templates, but I need to render the block inside the node body using PHP code, is there a way to do that?

We already tried:

\Drupal::moduleHandler()->invoke($module, $hook, $args = array())

but it doesn't show the block, presumably because it only takes modules?

From this answer we also tried:

$block = \Drupal\block_content\Entity\BlockContent::load($bid); 
$render = \Drupal::entityTypeManager()->getViewBuilder('block_content')->view($block);

Trying to print or render $render either doesn't show anything or literally prints out an array.

  • 3
    Possible duplicate of How can I programmatically display a block?
    – Beebee
    Commented Oct 26, 2017 at 13:23
  • Is it a block provided by a module or is it a custom content block? (Content block = You went to Structure > Block Layout > Custom block library > Add custom block). If it's a module block, use block view builder instead of block_content.
    – Beebee
    Commented Oct 26, 2017 at 13:36
  • @Beebee just tried with block, same behaviour. Printing $render just prints an array, rendering it doesn't show anything :(
    – user56564
    Commented Oct 26, 2017 at 13:44
  • You shouldn't even need to render it. Where's the code placed? It should be in THEME_preprocess_node. Just add it to $variables as $variables['mycustomblock'] = $render and in node.twig.html print it out with {{ mycustomblock }}
    – Beebee
    Commented Oct 26, 2017 at 13:58
  • @Beebee the code is directly in the node body, the thing is it's content specific so we can't put it in a template
    – user56564
    Commented Oct 26, 2017 at 14:01

1 Answer 1


You can do the following:

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 %}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.