Include template
Many developers prefer to store header/footer code in a separate file and include that file in page.html.twig
.
Process
Let’s say you’ve created the following file in your theme’s folder for the header:
THEME_NAME/templates/includes/header.html.twig
And now you want to include this file in:
page.html.twig
Recommended Method
The proper method for Drupal 8 themes is to use Twig namespaces to reference the current theme’s "templates" directory. Here’s an example:
{% include '@THEME_NAME/includes/header.html.twig' %}
Below is an example from a working theme on Drupal.org called Architect.
“@architect” refers to the /templates directory inside the working theme (architect).
{% include '@architect/includes/header.html.twig' %}
The Twig namespace is created automatically in Drupal 8 when your theme is installed and points to your theme’s /templates
directory. Essentially, writing “@theme_name” in a Twig include (as shown above) will reference the location your_site.com/themes/theme_name/templates
on your server.
Not Recommended Method
One possible (but not recommended) method is to use the following code to include the file.
{# NOT recommended #}
{% include directory ~ '/templates/includes/header.html.twig' %}
The above may work, but it will result in a server error when used with a subtheme.
Extending Namespace Functionality
The Component Libraries module provides more flexible and advanced organization of Twig templates in Drupal 8, which can work well with Twig's "embed" functionality.
Drupal’s online documentation is © 2000-2020 by the individual contributors and can be used in accordance with the Creative Commons License, Attribution-ShareAlike 2.0. PHP code is distributed under the GNU General Public License.