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:
And enable with Drush:
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:
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:
This will return:
So the block ID I need is
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
Using my example from above, I can add the Profile Block to the Twig template with:
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
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!