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
    Commented May 4, 2018 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. Commented May 11, 2018 at 15:00

2 Answers 2


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

  • 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. Commented May 7, 2018 at 8:32
  • So you can just use the function behind this twig function named drupalEntity in twig_tweak/src/TwigExtension.php. Commented Dec 24, 2020 at 10:07
  • The following function for twig tweak works like a charme by the way. Commented Dec 24, 2020 at 10:13

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

Your Answer

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

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