Understanding Twig Context or Scope

A few exercises to navigate Twig context or scope and how it works.

Craft 3, Craft 4

Twig

A ques­tion came up recent­ly on Dis­cord about how to access the path and name of a child a tem­plate with­in a par­ent tem­plate. The Dis­cord user want­ed to get the path and tem­plate name of a child tem­plate in the par­ent tem­plate the child tem­plate extended.

The answer is to use the _self key­word, which will out­put a string of the tem­plate path, rel­a­tive to the templates direc­to­ry and the tem­plate name. 

{{ _self }} {# outputs templatePath/templateName #}

Of course, that will out­put the tem­plate name and path of the tem­plate in which you use _self, so to get the tem­plate name in the par­ent tem­plate, we need assign it a Twig vari­able and then that vari­able is added to the active con­text or scope, so it and its val­ue are avail­able in any template.

We have to set this out­side of any blocks in our tem­plate because those cre­ate a dif­fer­ent context:

{% set templatePathAndName = _self %}
{{ dump(_context) }}

Then you can out­put the vari­able val­ue in the par­ent tem­plate and get the path of the child template.

{{ templatePathAndName }}

That’s the solu­tion to the prob­lem asked by the Dis­cord user.

But it’s also a good entry point into learn­ing about Twig scope or con­text, so I want to use this exam­ple that came up in the Dis­cord serv­er to revis­it scope or con­text in Twig again.