CraftQuest Articles

Tutorials, tips, and thoughts on Craft CMS, modern web development, and more.

Image

Passing Data with a Twig Include Statement

Posted on Feb 24, 2019 by Ryan Irelan

Reading time: 1 minute, 7 seconds

The Twig include state­ment is a fan­tas­tic lit­tle tool because it allows us to fur­ther (in addi­tion to extends) chunk our tem­plate code into small­er, reusable pieces. 

It’s a sim­ple state­ment that does two things:

  1. Pulls in an exter­nal tem­plate in the flow of the par­ent template.
  2. Acts as a trans­porter of data from the par­ent tem­plate to the includ­ed template.

In this les­son we’re going to talk about the sec­ond one.

The Default Scope #

By default the Twig include sets the scope of avail­able data to all vari­ables avail­able glob­al­ly in the par­ent template.

As an exam­ple, if I set a vari­able named title at the top of my tem­plate that has the val­ue of the cur­rent entry title (assum­ing we’re on a entry view in Craft CMS or any oth­er CMS):

{% set title = entry.title %}

By default, this title vari­able is con­sid­ered in scope for any include tem­plate (in the par­lance of Twig, they call this the active context”). 

{% include '_includes/year_archive' %}

There’s noth­ing to pass or del­care; it hap­pens automatically.

Explic­it­ly Pass­ing Data #

In addi­tion to hav­ing access to data in the active con­text” we can also explictliy pass data to a tem­plate via the include statement.

We do this using the with keyword.

{% include '_shared/year-archive-list' with {'batchCount': 6} %}

In this exam­ple we are pass­ing a hash with the key of batchCount and the val­ue of 6 via the include state­ment. This is now avail­able in the includ­ed tem­plate using the vari­able batchCount.

Exclud­ing Data #

The include state­ment also has the only key­word, which allows us restrict the data that is passed into the includ­ed template.

The vari­a­tions of this are as follows:

{% include '_shared/_year-archive-list' only %}

This vari­a­tion dis­ables the active con­text” that we talked about ear­li­er. None of the active con­text data will be avail­able in the includ­ed tem­plate. This includes the title vari­able we set earlier.

{% include '_shared/_year-archive-list' with {'title': 'News Year Archive'} only %}

This vari­a­tion still restricts data from the active con­text” but also includes only the data we explic­it­ly set in the hash (the page title).

If you want to learn more about using include in a pow­er­ful way, check out the Flex­i­ble Twig Tem­plates in Craft course right here on CraftQuest.

© 2018 Mijingo, LLC