【发布时间】:2019-11-08 19:45:20
【问题描述】:
我想在渲染模板时将变量从 python 传递给 jinja2。
'with_remediation' 是一个布尔值/变量,我想将其传递到 jinja2 模板中进行评估。
这是 jinja2 模板文件的样子:
{% if with_remediations %}
no hostname
{% endif %}
hostname {{ nodes.hostname }}
在我的渲染函数中,我有这些代码行:
with_remediation = True
baseline = env.get_template(template)
config = baseline.render(nodes = node_object[index],with_remediation)
当我执行代码时,出现以下错误:
config = baseline.render(nodes = node_object[index],with_remediation)
SyntaxError: non-keyword arg after keyword arg
但是,如果我直接在函数调用中指定布尔值:
config = baseline.render(nodes = node_object[index],with_remediation=True)
它运行没有错误,但不是预期的输出。
这是执行时的输出:
switch
/templates/cisco/ios/switch/test.jinja2
Push configs? [y/N]: y
config term
Enter configuration commands, one per line. End with CNTL/Z.
switch(config)#
switch(config)#
switch(config)#
switch(config)#
switch(config)#hostname switch
switch(config)#end
switch#
预期的结果应该是:
switch
/templates/cisco/ios/switch/test.jinja2
Push configs? [y/N]: y
config term
Enter configuration commands, one per line. End with CNTL/Z.
switch(config)#
switch(config)#no hostname
switch(config)#
switch(config)#
switch(config)#hostname switch
switch(config)#end
switch#
为什么它不执行 {% if with_remediations %} 部分,因为它成立?
【问题讨论】:
-
因为你传入的是
with_remediation而不是with_remediations请注意末尾的“s”。 -
另外,出现第一个错误的原因是 jinja 期望 keyword arguments 用于
render()函数。如果您有多个要传递给模板的变量,您可以将它们收集在一个字典中并传递给render()函数。 -
感谢@jordanm 的捕获。我解决了这个问题,现在它正在运行 {% if with_remediation %} 部分。但是,我不能像 arghol 提到的那样简单地传递变量。请给我一个例子,说明如何将一个变量与多个变量传递给 render()?我不太明白...
-
kwargs = {'with_remediations': True, 'nodes': node_object[index]}; baseline.render(**kwargs) -
谢谢乔丹。 @arghol 你有其他传递变量的方法吗?