Instantiate and load a block programmatically in twig template 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.
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(&amp;$variables) {
 $block = \Drupal\block\Entity\Block::load('block_id');
  if ($block) {
    $variables['my_custom_block'] = \Drupal::entityTypeManager()-&gt;getViewBuilder('block')-&gt;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.