Search code examples
pythonjinja2

Sum elements of the list in Jinja 2


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)?


Solution

  • 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.

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