A few exercises to navigate Twig context or scope and how it works.
Craft 3, Craft 4
A question came up recently on Discord about how to access the path and name of a child a template within a parent template. The Discord user wanted to get the path and template name of a child template in the parent template the child template extended.
The answer is to use the _self
keyword, which will output a string of the template path, relative to the templates
directory and the template name.
{{ _self }} {# outputs templatePath/templateName #}
Of course, that will output the template name and path of the template in which you use _self
, so to get the template name in the parent template, we need assign it a Twig variable and then that variable is added to the active context or scope, so it and its value are available in any template.
We have to set this outside of any blocks in our template because those create a different context:
{% set templatePathAndName = _self %}
{{ dump(_context) }}
Then you can output the variable value in the parent template and get the path of the child template.
{{ templatePathAndName }}
That’s the solution to the problem asked by the Discord user.
But it’s also a good entry point into learning about Twig scope or context, so I want to use this example that came up in the Discord server to revisit scope or context in Twig again.