在 Jinja2 中导入/包含分配的变量
在 Jinja2 中,如何访问包含 include
的文件中指定的变量(即 {% set X=Y %}
)?
我希望在给定两个 Jinja2 文件的情况下可以执行以下操作:
A.jinja
:
Stuff
{% include 'B.jinja' -%}
B has {{ N }} references
B.jinja
:
{% set N = 12 %}
我希望 A.jinja
,当使用 Jinja2 编译时,会产生以下输出:
Stuff
B has 12 references
然而,它会产生:
Stuff
B has references
我非常感谢有关如何访问文件中的 Jinja2 变量的任何输入,例如上面的 N
其中包括设置 N
的文件。
感谢您的阅读。
布莱恩
In Jinja2, how can one access assigned variables (i.e. {% set X=Y %}
) within files incorporated with include
?
I'd expect the following to work given two Jinja2 files:
A.jinja
:
Stuff
{% include 'B.jinja' -%}
B has {{ N }} references
B.jinja
:
{% set N = 12 %}
I'd expect that A.jinja
, when compiled with Jinja2, would produce the following output:
Stuff
B has 12 references
However, it produces:
Stuff
B has references
I'd be much obliged for any input as to how to access the Jinja2 variables, such as N
above, in the file that includes the file where N
is set.
Thank you for reading.
Brian
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
include
和import
之间存在差异,尽管您应该能够同时执行这两种操作。include 'B.jinja
只是渲染模板并忽略其中的任何变量赋值或宏。import 'B.jinja' as B
,导入B
就好像它是一个模块,所以你必须输出BN
。from 'B.jinja' import N
直接导入变量N
。将导入行更改为最后一个选项,看看是否可以解决问题。如果您需要更多帮助,请查看文档。
There's a difference between
include
andimport
, although you should be able to do both.include 'B.jinja
simply renders the template and ignores any variable assignments or macros within it.import 'B.jinja' as B
, importsB
as if it were a module, so you have to outputB.N
.from 'B.jinja' import N
imports variableN
directly.Change your import line to the last option and see if that fixes things. If you need more help, look at the documentation.