Need to reuse HTML in multiple templates? Try using partial Twig templates

You have a piece of HTML code that needs to be included in multiple Twig templates. The code will be consistent across all of them - if you need to change it, you need to change it everywhere it is used.

As an example, I recently had to include a piece of code from a social share service called RhythmOne. I want to include this code in some, but not all, of the node templates.

A solution

Twig has the ability to add partial templates to another template. To add a partial template, use the include statement and the filename of the template.

Step by step

  1. In your theme, create a directory inside the templates directory called includes
  2. In the includes directory, create a Twig file for your partial template. For example, rhythmone.html.twig' 
  3. In the file you created in step two, add any code you need
  4. Go to the Twig template where you want to include the partial template. For example, a node template
  5. Include the partial template with:
 % include 'rhythmone.html.twig' %
  1. Repeat for any other templates where you need the same partial template

Drupal will automatically look in the template/includes directory in your theme.

Including templates from another theme or module

If you need to include a template from another theme or module, the syntax is slightly different.

If the partial template that you are including is stored anywhere other than the theme you are including it from, Drupal would not know where to find it with:

 {% include 'rhythmone.html.twig' %}

You could add the full path to the template, but that can be long winded.

To get around this, Twig has a concept called namespaces. This is very similar to PHP namespaces in modules. A namespace creates a short cut to the relevant template directory.

Modules and themes in Drupal have Twig namespaces that you can use. This will create short cut to the templates directory inside the relevant module or theme directory.

Let’s look at an example. If you have partial template in a module called mypages, then you can include it in another template in a different module, or theme, with:

 {% include '@mypages/includes/rhythmone.html.twig' %}

The @mypages part of the above code is a Twig namespace. It is made up of:

  • @
  • mypages: the name of the theme or module

The path after the namespace (@mypages) does not need “templates” because Drupal assumes that that is where your templates are stored.

One of the big advantages of using partial templates like this is that if you need to update the code, you only need to change it in one place.

Add new comment