How to render blocks in twig files
Blog

How to render blocks in twig files

After lot of research, finally got the way to render blocks in twig files.

Basically there are two type of renders.

  1. When there is an existing instance of the block in the layout. The the block can be rendered in twig using preprocess as
    $block = Block::load('mediablock');
      $variables['social_links'] = \Drupal::entityTypeManager()
        ->getViewBuilder('block')
        ->view($block);
    
  2. There is no instance or configurations for the block. Then in the preprocessor we need to create the instance, build the block and then render it
    $block_manager = \Drupal::service('plugin.manager.block');
      $config = [];
      $plugin_block = $block_manager->createInstance('farmjournal_social_sharing', $config);
      $render = $plugin_block->build();
      $variables['farmjournal_social_sharing'] = render($render);