简体   繁体   中英

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.

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 eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM