Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从python向jinja2传递变量_Python_Jinja2 - Fatal编程技术网

从python向jinja2传递变量

从python向jinja2传递变量,python,jinja2,Python,Jinja2,我想在呈现模板时将变量从python传递到jinja2 “with_rectification”是一个布尔值/变量,我希望将其传递到jinja2模板中进行评估 以下是jinja2模板文件的外观: {% if with_remediations %} no hostname {% endif %} hostname {{ nodes.hostname }} 在我的渲染函数中,我有以下几行代码: with_remediation = True baseline = env.get_templa

我想在呈现模板时将变量从python传递到jinja2

“with_rectification”是一个布尔值/变量,我希望将其传递到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_remeditions%}部分,因为它是真的?

因为您传入了
with_remedition
而不是
with_remeditions
请注意结尾的“s”。此外,出现第一个错误的原因是jinja需要
render()
函数。如果您有多个要传递给模板的变量,您可以在dict中收集这些变量并传递给
render()
函数。谢谢您的catch@jordanm。我修复了这个问题,现在它正在运行{%if with_reception%}部分。但是,我不能像arghol提到的那样简单地传入变量。请给我一个例子,说明如何将一个变量与多个变量传递到render()?我不太明白…
kwargs={'with_remeditions':True,'nodes':node_object[index]};baseline.render(**kwargs)
谢谢jordanm@你们有不同的方法来传递变量吗?你们能解释一下这里发生了什么吗?另外,第一段看起来是HTML模板,第二段是Python代码,但它的格式并没有使之成为HTML模板clear@SamMason杰耶什说得对。本质上,我只是将'boo'传递到render_template()函数中,而没有指定with_recoveration=boo。请检查我上面的评论。
{% if with_remediations %}
Works when condition is true //Any Statement
{% else %}
no hostname //Any Statement
{% endif %}

def demo():
boo=True`
  return render_template("demo.html",with_remediations=boo)