Sum of list items in Jinja 2
I have a list in Jinja2 that contains the dicts themselves. Something like
items = [{'name':'name1', 'points':5}, {'name':'name2', 'points':7},
{'name':'name3', 'points':2}, {'name':'name4', 'points':11}]
I need to get the sum of all points and print them somewhere later.
Currently I got:
{% set points = 0 -%}
{% for single_item in items -%}
{% set points = points + single_item["points"] -%}
{{points}}
{% endfor %}
{{ points }}
Result: 5 12 14 25 0
Is there any way I can get the points outside the loop to have a value of 25 (the last value from the loop)?
source to share
I was able to get it to work, although the solution is not elegant, but it works:
{% set points = [0] -%}
{% for single_item in items -%}
{% if points.append(points.pop()+ single_item["points"]) -%}{% endif %}
{% endfor %}
{{ points }}
points will be an array with only one element that has a sum.
This can be done with the added do extension and will replace the {% if%} line.
source to share
Jinja2 includes a sum filter that will do this for you:
{{ items | sum(attribute='points') }}
See the documentation here: http://jinja.pocoo.org/docs/dev/templates/#sum
source to share
This kind of logic should usually go in the controller and not in the template (separating the logic from the view). Pre-process your data and pass the elements as well as the total to the template:
from jinja2 import Template
template = Template(open('index.html').read())
items = [{'name': 'name1', 'points': 5},
{'name': 'name2', 'points': 7},
{'name': 'name3', 'points': 2},
{'name': 'name4', 'points': 11}]
total = sum([i['points'] for i in items])
print template.render(items=items, total=total)
index.html
<table>
{% for item in items %}
<tr>
<td>{{ item.name }}</td>
<td>{{ item.points }}</td>
</tr>
{% endfor %}
</table>
<strong>Total:</strong>{{ total }}
For more information on expression, sum([i['points'] for i in items])
see the list of concepts .
source to share