列表中元素的总和在Jinja 2 [英] Sum elements of the list in Jinja 2

查看:60
本文介绍了列表中元素的总和在Jinja 2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Jinja2中有一个列表,它本身包含字典.像

I have list in Jinja2 that contain dicts in itself. Something like

items = [{'name':'name1', 'points':5}, {'name':'name2', 'points':7}, 
 {'name':'name3', 'points':2}, {'name':'name4', 'points':11}]

我需要获取所有的总和并在以后打印它.

What I need is to get sum of all points and to print it somewhere later.

目前我得到的是:

{% set points = 0 -%}
{% for single_item in items -%}
    {% set points = points + single_item["points"] -%}
    {{points}}
{% endfor %}
{{ points }}

结果是:5 12 14 25 0

Result is: 5 12 14 25 0

有什么方法可以使循环外的具有值 25 (循环中的最后一个值)?

Is there any way that I can get that points outside of loop has value 25 (last value from the loop)?

推荐答案

我设法使它起作用,尽管解决方案不是很好,但它正在起作用:

I've managed to make it work, although solution is not elegant, but it is working:

{% set points = [0] -%}
{% for single_item in items -%}
    {% if points.append(points.pop()+ single_item["points"]) -%}{% endif %}
{% endfor %}
{{ points }}

将是仅包含一个具有和的元素的数组.

points will be array with just one element that has sum.

也可以使用包含的 do 扩展名来完成,它将替换{%if%}行.

It can be also done with included do extension, and that would replace {% if %} line.

这篇关于列表中元素的总和在Jinja 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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