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

Malabya Tewari

Malabya joined Valuebound as Drupal developer but eventually moved from just being a Drupal backend developer to a near full-stack developer. From devops to front-end and from project management to project delivery, he has tasted nearly all the fields in software development. Apart from coding he likes to laze around with his laptop digging into new technologies or watching YouTube.
More about Malabya Tewari

comments powered by Disqus