0

I created a simple block that shows some text grabbed from an external source, and it renders as expected when I place it from the back-end (Structure->Block Layout).

But I want to be able to place it via code only inside a twig template from the theme directory. I thought I would use {{ drupal_block('id defined in Block.php') }} from the Twig tweak module but it never works unless the block is first placed from the back-end which assigns it a machine name then I can display it anywhere using that machine name in drupal_block() instead of the id I defined in its source code.

So how can I instantiate it programmatically first and then place it the the twig template I want?

During my search I came across Plugin Derivatives, I don't know if it is the solution I want, or how to use it.

1

I am sure there are other ways to solve this problem, but here is how I would do it.

Create your block, then go to admin/structure/block and place your block under "Disabled" list. You can then implement hook_preprocess_node in your .theme.php file.

theme file:

/**
 * Implements hook_preprocess_node()
 */

function mytheme_preprocess_node(&$variables) {
 $block = \Drupal\block\Entity\Block::load('block_id');
  if ($block) {
    $variables['my_custom_block'] = \Drupal::entityTypeManager()->getViewBuilder('block')->view($block);
  }
}

In your template twig file:

{% if my_custom_block %}
 {{ my_custom_block }}
{% endif %}

You just have to make sure that your block_id correct.

  • I like the approach, though I never saw a 'disabled' section in Drupal 8. – Neograph734 Jun 25 '17 at 21:15
  • Unfortunately it doesn't work... If I disable the block it disappears whether using drupal_block() or preprocess_node(). Your twig code is missing a % at the opening if block and there is an extra space at the closing block. – sandrows Jun 27 '17 at 11:45

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.