Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum elements of the list in Jinja 2

Tags:

python

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.

Currently what I got is:

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

Result is: 5 12 14 25 0

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

like image 838
Perun Avatar asked Aug 27 '14 10:08

Perun


2 Answers

Jinja2 includes a sum filter which will do this for you:

{{ items | sum(attribute='points') }}

See documentation here: https://jinja.palletsprojects.com/templates/#jinja-filters.sum

like image 155
Bartlett Avatar answered Oct 13 '22 13:10

Bartlett


That sort of logic should usually go in the controller, not the template (separating logic from presentation). Preprocess your data accordingly, and pass items as well as 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 details on the expression sum([i['points'] for i in items]) see list comprehensions.

like image 41
Lukas Graf Avatar answered Oct 13 '22 14:10

Lukas Graf