How do you place a block in a Twig template

There are various ways you can add blocks to regions in pages in Drupal. You could add it in the block interface, use Panels or Context. But what if you just want to place a block directly in a Twig template?

The simplest way to place a block in a Twig template is to use the Twig Tweak module. Twig Tweak is a very handy module that gives you a range of functions to make theming with Twig easier.

Install Twig Tweak

Go ahead and install the Twig Template module. You can download it with composer and enable it with Drush:

composer require drupal/twig_tweak

And enable with Drush:

drush en twig_tweak

Find the block ID

To add the block using Twig Tweak, you need to know the ID of the block. There are a few ways to find the block ID. I find the easiest way is to use the following Drush command, which will return a list of all blocks with their respective ID’s:

drush ev "print_r(array_keys(\Drupal::service('plugin.manager.block')->getDefinitions()));" 

If you know part of the ID, you can search for it by adding grep to the end. For example, I have a block that I know has “profile” in the ID, but I don’t know the full ID. I can find it my using this command:

drush ev "print_r(array_keys(\Drupal::service('plugin.manager.block')->getDefinitions()));" | grep profile

This will return:

[28] => profile-block

So the block ID I need is profile-block.

Use the Twig Tweak drupal_block() function

Now that you have the ID for the block, the next step is to place the block in the Twig template with the drupal_block() function.

{{ drupal_block('blockid') }}

Using my example from above, I can add the Profile Block to the Twig template with:

{{ drupal_block('profile-block') }}

Alternative methods

There a few alternatives to using Twig Template, which you may consider depending on your needs:

  • Add the block in the core block interface
  • Use Panels or Context to assign the block to a region
  • Add the block to a variable in a pre-process function and add that variable to your Twig template

Wrapping up

As you’ve seen in this tutorial, using Twig Tweak makes it relatively simple to place a block in a Twig template. All it takes is one line of code!

If you liked this, you'll love my book, Conquer Drupal 8 Module Development.

Add new comment