Jinja 无法调用函数

Jinja cannot Call function

我试图在 jinja 中制作一个简单的宏,然后用 {{messageRed('TEST')}} 调用它,但无论我做什么,它都不起作用。它也不会将计数器递增到 +1。最后我得到了输出:

Compliance Score: 0

Expected Output: Compliance Score: 1 TEST

代码如下:

{%set counter = 0 %}

{%set msgRed = ''%}

{%macro messageRed(msg) -%}
    {%set counter = counter + 1%}
    {%set msgRed = msgRed + '<p style="color: red;">' + msg + '</p>'%}
{%- endmacro%}

{{messageRed('TEST')}}

<h3>Compliance Score: <b> {{counter}} </b></h3><hr>{{msgRed}}

根据 Internet 上的信息 macro 无法更改外部元素 - 这是正常的 documented 行为 - 寻找 scope.

所以它不仅不能改变外部值而且如果你运行它几次那么你总是得到相同的值。可能就像在普通函数中一样,它会在每次 运行 宏时一次又一次地创建这个(本地)变量。

在回答问题How to increment a variable on a for loop in jinja template?时有人建议将其定义为

{% set count = namespace(value=0) %} 

并更改值

{% set count.value = count.value + 1 %}

并显示出来

{{ count.value }}

它对我有用。

msgRed也是如此。

{%set msgRed = namespace(text="") %}

{%set msgRed.text = msgRed.text + '<p style="color: red;">' + msg + '</p>'%}

{{ msgRed.text }}

这里是我用来测试它的最小工作代码: 从 jinja2 导入模板

tm = Template("""
{%set counter = namespace(value=0) %}

{%set msgRed = namespace(text="") %}

{%macro messageRed(msg) -%}
    {%set counter.value = counter.value + 1%}
    {%set msgRed.text = msgRed.text + '<p style="color: red;">' + msg + '</p>'%}
{%- endmacro%}

{{messageRed('TEST')}}
<h3>Compliance Score: <b> {{counter.value}} </b></h3><hr>{{msgRed.text}}

{{messageRed('TEST')}}
<h3>Compliance Score: <b> {{counter.value}} </b></h3><hr>{{msgRed.text}}

{{messageRed('TEST')}}
<h3>Compliance Score: <b> {{counter.value}} </b></h3><hr>{{msgRed.text}}

""")

msg = tm.render()

print(msg)

结果

<h3>Compliance Score: <b> 1 </b></h3><hr><p style="color: red;">TEST</p>
    
<h3>Compliance Score: <b> 2 </b></h3><hr><p style="color: red;">TEST</p><p style="color: red;">TEST</p>
    
<h3>Compliance Score: <b> 3 </b></h3><hr><p style="color: red;">TEST</p><p style="color: red;">TEST</p><p style="color: red;">TEST</p>