Can a Jinja variable's scope extend beyond in an inner block?

后端 未结 8 915
夕颜
夕颜 2020-11-27 06:07

I have the following Jinja template:

{% set mybool = False %}
{% for thing in things %}
    
    {%
8条回答
  •  余生分开走
    2020-11-27 06:44

    Here's the general case for anyone wanting to use the namespace() object to have a variable persist outside of a for loop.

    {% set accumulator = namespace(total=0) %}
    {% for i in range(0,3) %}
        {% set accumulator.total = i + accumulator.total %}
        {{accumulator.total}}
     {% endfor %}`          {# 0 1 3 #}
     {{accumulator.total}}  {# 3 (accumulator.total persisted past the end of the loop) #}
    

提交回复
热议问题