递增变量时重置Jinja for循环范围 [英] Jinja for loop scope is reset when incrementing variable

查看:64
本文介绍了递增变量时重置Jinja for循环范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建Flask应用,并试图在订单行中循环显示篮子中的物品数量.

I am building a Flask app and am trying to loop through order lines to display the amount of items in a basket.

{% set items = 0 %}
{% for line in current_order.order_lines %} #loops twice in current test
    {% set items = items + line.quantity %} #should add 5 then 2
{% endfor %}

{{ items }} #outputs 0

经过研究后,我发现这是一个范围问题,即最下面的{{ items }}看不到我先加5再加2.如何在Jinja for循环中增加一个值?

After some research I've found it is a scope issue, i.e. the bottom {{ items }} can't see that I have added 5 then 2. How can I increment a value in a Jinja for loop?

推荐答案

这确实是一个范围界定问题,因为 Jinja2模板参考中记录的:

This is indeed a scoping issue, as documented in the Jinja2 template reference:

作用域行为

请记住,无法在块内设置变量并使变量显示在块外.这也适用于循环.

Scoping Behavior

Please keep in mind that it is not possible to set variables inside a block and have them show up outside of it. This also applies to loops.

[...]

从2.10版开始,可以使用namespace对象处理更复杂的用例,这些对象允许在范围内传播更改.[.]

As of version 2.10 more complex use cases can be handled using namespace objects which allow propagating of changes across scopes[.]

因此,您可以将 namespace()用作工作-周围:

So you could use the namespace() class as a work-around:

{% set ns = namespace(items=0) %}
{% for line in current_order.order_lines %}
    {% set ns.items = ns.items + line.quantity %}
{% endfor %}

{{ ns.items }}

也就是说,如果您先计算商品计数 并将其作为current_order对象或其他上下文的一部分传递到模板中,那就更好了.

That said, it is much better if you calculated the item count up front and passed this into the template as part of the current_order object or additional context.

另一种选择是使用 sum()过滤器对那些求和数量:

Another option is to use the sum() filter to sum those quantities:

{% for line in current_order.order_lines %} #loops twice in current test
    <!-- render order line -->
{% endfor %}

{{ current_order.order_lines|sum(attribute='quantity') }}

这篇关于递增变量时重置Jinja for循环范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆