Including Part Template

Last updated on
18 January 2018

Many themers prefer to keep header / footer codes in a separate file and call the file in page.html.twig

Let's say you have created following file in your theme folder for header.
/THEME_NAME/templates/includes/header.html.twig

And now you want to include this file in page.html.twig

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

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

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

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

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

The above example is taken from a working theme on Drupal.org called "Architect". In this example, "@architect" refers to /templates in the working theme directory.  

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.