Base on information on internet macro
can't change external elements - and it is normal and documented behavior - look for scope
.
So it not only can't change exteranl value but also if you run it few times then you always get the same value. Probably like in normal function it create this (local) variable again and again every time when you run macro.
In answer to question How to increment a variable on a for loop in jinja template? someone suggests to define it as
{% set count = namespace(value=0) %}
and change value
{% set count.value = count.value + 1 %}
and display it
{{ count.value }}
And it works for me.
The same is with msgRed
.
{%set msgRed = namespace(text="") %}
{%set msgRed.text = msgRed.text + '<p style="color: red;">' + msg + '</p>'%}
{{ msgRed.text }}
Here minimal working code which I used to test it:
from jinja2 import Template
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)
Result
<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>