I'm trying to find a solution to embed a drupal custom block using PHP. I found this snippet that works :

$block = \Drupal\block\Entity\Block::load('your_block_id');
$render = \Drupal::entityTypeManager()->getViewBuilder('block')->view($block);
print render($render);

The problem is that this code directly render the block content, I don't have any contextual links for that block. My question is, how to render the whole block (including contextual links), exactly like if I added it in a region using the UI.

Thank you

  • That should do it, the contextual links are added in preprocess. Have you confirmed that when you add the same block into a region through the UI the contextual links are rendered? – Clive May 4 '18 at 10:02
  • Added thanks to the UI, the contextual links are rendered. It's when I try to render using php that contextual links are not added. – Alexandre Zeiller May 11 '18 at 15:00

You can use the Twig Tweak module to insert the 'local tasks' menu in your template file:

{{ drupal_entity('block', 'THEME_local_tasks', check_access=true) }}

|improve this answer|||||
  • Hello, Thank you for the tips, but I need to do it using php. I'm not on the template file to do that. I know this is not ideal, but I don't have choice. – Alexandre Zeiller May 7 '18 at 8:32

This is an open issue. Block Content entities have no Contextual links when rendered outside of Block config entity: https://www.drupal.org/project/drupal/issues/2666578

|improve this answer|||||

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.