0
votes

im trying to use a for loop to add up some numbers for each day and i would like to access the variable outside the for loop im not sure how to go about this I am using the flask framework with python and just come from weppy where this was not a problem is there a way to make it work the same way in flask?

here is some simple code

{% set newtotal = 0 %}
{% for item in daily: %}
    {% set newtotal = newtotal + item[10]|float %}
{% endfor %}

<div class="bottom">
    <span>Total: {{ newtotal }}</span>
</div>

the numbers collected by item[10] are dollar values if i place the {{ newtotal }} before the endfor it shows every value as its being added up this is not what I want

EDIT: if it helps daily is a list of 8 tuples

2
Can you pass in a variable named "newtotal" that is equal to the len(daily) (that you would calculate in your Python server script)? - cosinepenguin
this is basically what i ended up doing thats for the hint ;) - Mike

2 Answers

1
votes

One solution (probably the "simplest") would be to change your Python script to pass in a variable named newtotal that would simply be the length of the daily list!

Alternatively, you could use the length filter:

{{things|length}}

In which case your code could look something like this:

{% set newtotal = 0 %}
{% for item in daily: %}
    {% set newtotal = newtotal + item[10]|float %}
{% endfor %}

<div class="bottom">
    <span>Total: {{daily|length}}</span>
</div>

Hope it helps!

Additional Sources:

jinja2: get lengths of list

How do I access Jinja2 for loop variables outside the loop?

EDIT

Sorry, I misread the question!

You can use the sum filter instead ({{ list | sum() }}).

So your code could look like:

{% set newtotal = 0 %}
{% for item in daily: %}
    {% set newtotal = newtotal + item[10]|float %}
{% endfor %}

<div class="bottom">
    <span>Total: {{ daily | sum() }}</span>
</div>

New sources:

Documentation Sum elements of the list in Jinja 2

1
votes

Please keep in mind that it is not possible to set variables inside a block or loop and have them show up outside of it. As of version 2.10 this can be handled using namespace objects which allow propagating of changes across scopes.

Here is your code using namespace:

{% set ns = namespace (newtotal = 0) %}
{% for item in daily: %}
    {% set ns.newtotal = ns.newtotal + item[10]|float %}

{% endfor %}

<div class="bottom">
    <span>Total: {{ ns.newtotal }}</span>
</div>