Including Part Template

Last updated on
10 January 2024

This documentation needs review. See "Help improve this page" in the sidebar.

Many themers prefer to keep header/footer codes in a separate file and call the file in page.html.twig.The Twig include tag is similar to PHP include function, in that the purposes is to include another file.

Process

Let's say you have created following file in your theme folder for the header:

THEME_NAME/templates/includes/header.html.twig

And now you want to include this file in:

page.html.twig

The correct method for Drupal 8 themes is to use Twig namespaces to declare the current theme "templates" directory. Here is an example:

{% include '@THEME_NAME/includes/header.html.twig' %}

Below is an example taken from a working theme on Drupal.org called Architect.
"@architect" refers to /templates in the working theme (architect) directory.  

{% include '@architect/includes/header.html.twig' %}

A Twig namespace is created in Drupal 8 automatically when installing your theme, and it points to the /templates directory of your theme. Essentially, writing "@theme_name" in a Twig include (like above) will reference the location "your_site.com/themes/theme_name/templates" on your server.

Additional parameters

If you want to pass additional arguments for loop or for checking some variables to your included twig template you should write in this way

{% include '@THEME_NAME/includes/form-block.html.twig' with {key: value} %}

Example:

{% include '@mytheme/includes/form-block.html.twig' with {display_title: true} %}

The not-recommended method

One possible (but not recommended) method is to use below code to include this file.

{# NOT recommended #}
{% include directory ~ '/templates/includes/header.html.twig' %}

The above information may work however it will create a server error if used with a sub-theme.

Extending namespace functionality

The component libraries contributed module allows more flexible and sophisticated twig template organization in Drupal 8, which can work with the twig "embed" statement.

Tags

Help improve this page

Page status: Needs review

You can: