templatesjinja2templatingnunjucksclient-side-templating

Nunjucks/Jinja - alternative for `include` when access to scope is needed


According to Nunjucks documentation,

an include is not a pre-processor that pulls the included template code into the including template before rendering; instead, it fires off a separate render of the included template, and the results of that render are included.

If you actually want a "pre-processor that pulls the included template code into the including template before rendering", what that would be in Nunjucks/Jinja?


Practical example would be: two partials have same variables being set. We decide to DRY it up, putting those set statements into a partial and requesting it via include. When using include those variables are out of scope.

partial-config.nunjucks:

{% set var = 'x' %}

partial1.nunjucks:

{% include "partial-config.nunjucks" %}
var={{ var }}

partial2.nunjucks:

{% include "partial-config.nunjucks" %}
var={{ var }}

Challenge: The variable var in partials above is blank. I want it to be set within each partial's scope, before rendering, as if it was only string snippet, without extra scopes etc.


Solution

  • Perhaps it's not possible because first render primary template and include after it. Maybe I wrong.

    In any case you can use custom loader, "define" your own tag e.g. config with usage like {% config "filename.njk" %}. Loader must find config-tag and replace this row by filename.njk and pass template to render next.