jinja2 中的 set value 命令在某些情况下有效,但在某些情况下无效

set value command in jinja2 works in some cases and not in some

以下代码显示不同月份的不同 x 值。 jinja2 的 set 命令适用于 flag,x 但不适用于 total。为什么?

    {% set flag = 1 %}
    {% set total = 0 %}
    {% for date in dates %} //dates is some array
        {% if flag == 1 %}
            {{x}}
            {% set flag= 0 %} // I have used 1+1 also that too works
        {% elif "Jul" in date %}
            {% set x = x*3 %}
            {% if x % 10!=0 %}
                {% set x = x - x % 10 %}
                {% set total = total + x %}
            {% endif %}
        {% else %}
            {{x}}
            {% set total = total + x %}
        {% endif %}
    {% endfor %}
    {{total}}

您在 模板 中的计算逻辑过于复杂:最好将该逻辑(或其部分)移动到 data-provider 组件。

例如,在数据提供者组件中,您可以为每个 data 计算 x,并将结果放入 data.x。然后{{dates|sum(attribute='x')}}会显示总值。