【问题标题】:Passing variables into jinja2 from python将变量从python传递到jinja2
【发布时间】: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 你有其他传递变量的方法吗?

标签: python jinja2


【解决方案1】:
{% 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)

【讨论】:

  • 你能补充一些关于这里发生了什么的解释吗?第一段看起来是 HTML 模板,第二段是 Python 代码,但它的格式不明确
  • @SamMason Jayesh 说得对。本质上,我只是将“boo”传递给 render_template() 函数,而没有指定 with_remediation=boo。请检查我上面的 cmets。
猜你喜欢
  • 1970-01-01
  • 2014-05-05
  • 2018-06-07
  • 2021-11-18
  • 2016-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多