On this page
Twig functions: template()
The Components module adds helpful Twig functions that can be used by any Twig template in Drupal.
The template() function
The template function includes the given template file name or Drupal theme hook.
Instead of calling Twig's include function with a specific Twig template, the template function will include the same Twig template, but after running Drupal's normal preprocess and theme suggestion functions.
Variables that you want to pass to the template should be given to the template function using named arguments. For example:
{{
template(
"item-list.html.twig",
title = "Animals not yet in Drupal core",
items = ["lemur", "weasel", "honey badger"],
)
}}
Note that template() returns a render array. This means you can filter it with Twig filters that expect arrays; e.g. template(...)|merge(...). If you want to use a filter that expects strings, you can use Drupal's render filter first; e.g. template(...)|render|stringFilter(...).
Alternatively, instead of the template name, you can pass a theme hook name or theme suggestion to the first argument:
{%
set list = template(
"item_list__node",
title = "Fictional animals not yet in Drupal core",
items = ["domo", "ponycorn"],
)
%}
Help improve this page
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion