Skip to main content

How to Express a Block as a Twig Variable (Drupal 8)

Front-end Development
Drupal

It’s not uncommon to have pages on a Drupal site with very specific layouts, requiring custom twig templating. But what do you do if you need to place a block with automated content between content-managed fields in the same region? How do you place that block within your twig template?

In this post I’m going to show you how to create a Twig variable for both a Views block and a custom block to place in your theme’s twig templates.

Views Block Twig Variable

In order to create a Twig variable of a Views block, we’ll need a preprocess function like this:

function mymodule_preprocess_node(&$variables) {
  $variables['VARIABLE_NAME'] = views_embed_view('VIEW_MACHINE_NAME', 'BLOCK_MACHINE NAME');
}

You can find the machine name of the view on the views admin page:

Table header of views admin page with the 'machine name' column highlighted

 

The machine name of the block you want to place can be found in the Advanced section of the view’s edit page:

Advanced column of views edit page with block machine name highlighted

 

Now you will be able to place your block your node twig template (or other template if you place it in a different preprocess function) using the variable you’ve declared:

{{ VARIABLE_NAME }}

Custom Block Twig Variable

This method involves creating a pseudo field that can be placed as a twig variable. The example below shows the steps to create a pseudo field for a taxonomy term, required due to the dynamic nature of the content.


/**
 * @file
 * Functions to create a pseudo field for a taxonomy page.
 */

/**
 * Implements hook_page_attachments().
 */
function mymodule_page_attachments(array &$attachments) {
  $attachments['#attached']['library'][] = 'module_name/moduleName';
  $attachments['#attached']['drupalSettings']['module_name'] = '';
}
/**
 * Implements hook_entity_extra_field_info().
 */
function mymodule_entity_extra_field_info() {
  $fields = [];
  $fields['taxonomy_term']['TERM_MACHINE_NAME']['display']['FIELD_VARIABLE_NAME'] = [
    'label' => t('Label Name'),
    'weight' => 100,
    'visible' => TRUE,
  ];
  return $fields;
}
/**
 * Implements hook_ENTIIY_TYPE_view().
 */
function mymodule_taxonomy_term_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display) {
  $markup = '';
  if ($display->getComponent('FIELD_VARIABLE_NAME')) {
    $build['FIELD_VARIABLE_NAME'] = [
      '#markup' => $markup,
    ];
    return $build;
  }
}

With this in place, we are able add the custom block to our twig template using the conventional field convention:

{{ content.FIELD_VARIABLE_NAME }}