1

I'm attempting to render a block plugin programmatically in a content type template. I understand how to render the block programmatically in a page template. like so

mytheme.theme

function mytheme_preprocess_page(&$variables){
    $myblock = \Drupal::service('plugin.manager.block')->createInstance('myblockid',[]);
    $variables['myblock'] = $myblock->build();

page.html.twig

<div class="my block">
{{ myblock }}
</div>

However in

node--contenttype.html.twig

<div class="my block">
{{ myblock }}
</div>

Produces nothing. Is there another hook I should be using? Or is there a better way to do this entirely?

3

I was able to accomplish this by placing the code into the preprocess node hook instead of the preprocess page. Like so

mytheme.theme

function mytheme_preprocess_node(&$variables){
    $myblock = \Drupal::service('plugin.manager.block')->createInstance('myblockid',[]);
    $variables['myblock'] = $myblock->build();
| improve this answer | |
  • 2
    Correct. Variables are not shared between those functions. – Kevin Jul 1 '16 at 19:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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