2

I'm pretty new to D8, so this might be basic stuff, but I can't find any tutorial how to do it.

In Drupal 7 this is the code that outputs core block in node.tpl.php:

<?php $block = module_invoke('block', 'block_view', '10'); print render($block['content']); ?>

This works for Views:

<?php print views_embed_view('viewname','block_10'); ?>

How do I achieve this in Drupal 8?

3
  • entity_load('block', $id)->view()
    – user21641
    Jan 9 '16 at 14:04
  • Could you please elaborate a bit?
    – take2
    Jan 10 '16 at 13:00
  • Sorry, that was wrong. It should be entity_load('block', $id)->getPlugin()->build();
    – user21641
    Jan 10 '16 at 14:02
11

In Drupal 8, you don't need (and should not) render in PHP. The rendering is done as late as possible in Twig.

So put the build array of your view in a variable.

function mytheme_preprocess_node(&$variables) {
  $variables['view1'] = views_embed_view('view1', 'block_news');
}

And then render it with {{ view1 }}.

Twig will handle the necessary rendering for all kind of render arrays that are possible in Drupal.

You can use the same for a block. (See the comment from Ivan Jaros.)

$variables['block1'] = entity_load('block', $id)->getPlugin()->build(); 

The build() method gives you the build array of the entity and you can use {{ block1 }}.

3
  • I wonder how to get that $id for the entity_load()
    – Adamtan
    Mar 15 '16 at 1:35
  • 'block' is a config entity and $id is the block config entity ID aka machine name. If you are looking for content, then use the entity 'block_content'
    – 4k4
    Mar 15 '16 at 7:37
  • How to output a view title this way? Aug 16 '16 at 8:09
1

If you have multiple blocks you can make a new region, place them there and use the following code.

function THEMENAME_preprocess_node(&$variables){
  $result = array();
  $blocks = \Drupal::entityManager()
            ->getStorage('block')
            ->loadByProperties(array('theme'  => 'THEMENAME', 
                                     'region' => 'YOUR_NEW_REGION'));

  foreach ($blocks as $key => $block) {
    if ($block->access('view')) {
      $result[$key] = entity_view($block, 'block');
    }
  }

  $variables['YOUR_NEW_VARIABLE'] = $result;
}

Then use {{ YOUR_NEW_VARIABLE }} in your template file.

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