Nunjucks/Jinja - 当需要访问范围时替代 `include`
Nunjucks/Jinja - alternative for `include` when access to scope is needed
根据 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.
如果你真的想要一个 "pre-processor that pulls the included template code into the including template before rendering",Nunjucks/Jinja 中会是什么?
实际示例是:两个部分具有相同的变量 set
。我们决定干掉它,将那些 set
语句放入部分并通过 include
请求它。使用 include
时,这些变量超出范围。
部分-config.nunjucks:
{% set var = 'x' %}
partial1.nunjucks:
{% include "partial-config.nunjucks" %}
var={{ var }}
partial2.nunjucks:
{% include "partial-config.nunjucks" %}
var={{ var }}
挑战:上面partials中的变量var
为空。我希望在渲染之前将它设置在每个部分的范围内,就好像它只是字符串片段,没有额外的范围等。
也许这是不可能的,因为首先渲染主模板,然后 include
。也许我错了。
在任何情况下,您都可以使用 custom loader、"define" 您自己的标签,例如config
用法类似于 {% config "filename.njk" %}
。加载程序必须找到 config
-tag 并将此行替换为 filename.njk
并传递模板以进行下一步渲染。
根据 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.
如果你真的想要一个 "pre-processor that pulls the included template code into the including template before rendering",Nunjucks/Jinja 中会是什么?
实际示例是:两个部分具有相同的变量 set
。我们决定干掉它,将那些 set
语句放入部分并通过 include
请求它。使用 include
时,这些变量超出范围。
部分-config.nunjucks:
{% set var = 'x' %}
partial1.nunjucks:
{% include "partial-config.nunjucks" %}
var={{ var }}
partial2.nunjucks:
{% include "partial-config.nunjucks" %}
var={{ var }}
挑战:上面partials中的变量var
为空。我希望在渲染之前将它设置在每个部分的范围内,就好像它只是字符串片段,没有额外的范围等。
也许这是不可能的,因为首先渲染主模板,然后 include
。也许我错了。
在任何情况下,您都可以使用 custom loader、"define" 您自己的标签,例如config
用法类似于 {% config "filename.njk" %}
。加载程序必须找到 config
-tag 并将此行替换为 filename.njk
并传递模板以进行下一步渲染。