The Twig include statement is a fantastic little tool because it allows us to chunk our template code into smaller, reusable pieces.
The Twig include
statement is a fantastic little tool because it allows us to further (in addition to extends
) chunk our template code into smaller, reusable pieces.
It’s a simple statement that does two things:
In this lesson we’re going to talk about the second one.
By default the Twig include
sets the scope of available data to all variables available globally in the parent template.
As an example, if I set a variable named title
at the top of my template that has the value of the current entry title (assuming we’re on a entry view in Craft CMS or any other CMS):
{% set title = entry.title %}
By default, this title
variable is considered in scope for any include
template (in the parlance of Twig, they call this the “active context”).
{% include '_includes/year_archive' %}
There’s nothing to pass or delcare; it happens automatically.
In addition to having access to data in the “active context” we can also explictliy pass data to a template via the include
statement.
We do this using the with
keyword.
{% include '_shared/year-archive-list' with {'batchCount': 6} %}
In this example we are passing a hash with the key of batchCount
and the value of 6 via the include
statement. This is now available in the included template using the variable batchCount
.
The include
statement also has the only
keyword, which allows us restrict the data that is passed into the included template.
The variations of this are as follows:
{% include '_shared/_year-archive-list' only %}
This variation disables the “active context” that we talked about earlier. None of the active context data will be available in the included template. This includes the title
variable we set earlier.
{% include '_shared/_year-archive-list' with {'title': 'News Year Archive'} only %}
This variation still restricts data from the “active context” but also includes only the data we explicitly set in the hash (the page title).
If you want to learn more about using include
in a powerful way, check out the Flexible Twig Templates in Craft course right here on CraftQuest.