Search code examples
pythonjinja2

How to add float values from array in for-loop in Jinja template?


I'm quite new to Python, so it's highely likely that my thinking is flawed on this matter. But I thought it would be quite simple to add some values together in a for-loop in a Jinja2 template. Due to reasons unknown to me, it can't be done with my rudimentair knowledge of this language. I hope you lot can help me with this.

I have an array with some floats in Python:

floatArray = [1.5,3.6,5.8,9.8,10,5.0]

I pass that array through in my template:

render_template("array.html", floatArray=floatArray,)

In my template I want to add these values together:

{% set total = 0.0 %}
        
{% for x in floatArray %}
    {% set total = x + total %}
    {{ x }} - {{ total }}<br>
{% endfor %}
<br>{{ total }}

This is the result I get:

1.5 - 1.5
3.6 - 3.6
5.8 - 5.8
9.8 - 9.8
10 - 10.0
5.0 - 5.0

0.0

What I expect is that the second column of the values will add up with the previous ones: 1.5, 5.1, 10.9, etc. The last number should be the total sum of the values: 35.7

For some reason the value of {{total}} resets itself after every iteration. Is there a way to prevent that from happening?

Of course I can use:

{{ float_array|sum() }}

But that won't be sufficient. I have several for loops in my code and I want to sum parts of those loops.

Please kick me in the right direction :)


Solution

  • The for statement creates a new scope in Jinja2. You can create a namespace variable instead to allow access to the variable from an inner scope:

    {% set ns = namespace(total=0.0) %}
    {% for x in floatArray %}
        {% set ns.total = x + ns.total %}
        {{ x }} - {{ ns.total }}<br>
    {% endfor %}
    <br>{{ ns.total }}