Includes in Twig
There are different ways to use an include in Twig. The easiest way is to just do a {% include ”template.html” %}.
This will give your included template full access to the current context in Twig and all the defined variables. However, if you change a variable from the parent context in the include, that won’t change the parent variable in contexts other than the included one.
Use include without the current context
You can make include work in isolation by explicitly setting the variables that can be used when calling the template with the only keyword.
This include can access the parent template’s context:
{% include 'template.html' with {'text': 'entry.text'} %}
But this one can not access the parent template’s context thanks to the only keyword:
{% include 'template.html' with {'text': 'entry.text'} only %}
The above include can only use the text variable.
Use include as a function
Another way to use an include is as a function call, this way we can for instance use the returned content with filters.
This is the recommended way in the docs.
Instead of using the only keyword we use with_context set to false
{% set output = include("template.html", {'text': 'entry.text'}, with_context=false) %}
{{ output | raw }}
Use an object with variables instead of defining them one by one
There are also a few good reasons to include the variables as part of an object.
This way the include code gets a bit cleaner:
{% set params = {
heading: block.heading,
text: block.text,
cases: block.cases
} %}
{% include("/_blocks/cases.html", { params }, with_context=false) %}
And you can merge the object with default values in the include:
{# -- Component default values merged with named arguments in 'params' from parent #}
{% set vars = {
heading: "",
text: "",
cases: null
} | merge(params) %}