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
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>
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
Use the namespace object.
https://jinja.palletsprojects.com/en/master/templates/#assignments
Here’s a working example from my config.
{% set i= namespace(fxp0_ip=0) %}
{% set i= namespace(mgmt_ip = 0) %}
{% set i= namespace(loopback_ip = 0) %}
{% set i= namespace(lan_ip = 0) %}
{% set i= namespace(wan_ip = 0) %}
{% for interface in device_vars.interfaces %}
{% elif interface.name == "ge-0/0/0" %}
{% set i.mgmt_ip = interface.ip_addr %}
{% elif interface.name == "lo0" %}
{% set i.loopback_ip = interface.ip_addr %}
{% elif interface.name == "ge-0/0/2" %}
{% set i.lan_ip = interface.ip_addr %}
{% elif interface.name == "ge-0/0/1" %}
{% set i.wan_ip = interface.ip_addr %}
{% endif %}
{% endfor %}
{{i.mgmt_ip}}
{{i.wan_ip}}
Related
{% for each_item in item.artifacts %}
{% if each_item.scanner_count > 0 and each_item.scanner_match > 0 %}
{% if forloop.counter <= 5 %}
<tr>
<td>{{each_item.threat_name}}</td>
</tr>
{% else %}
{% if forloop.last %}
<p><b><i> {{ forloop.counter|add:"-5" }} rows were truncated. See full report for more details. </i></b></p>
{% endif %}
{% endif %}
{% else forloop.counter -=1 %}
{% endif %}
{% endfor %}
ERROR:Malformed template tag at line 171: "else forloop.counter -=1"
I want to increment the counter only when if condition is successful. Dont know how to do it with forloop.counter. Goal is to print 5 rows of valid output(scanner count >0 and Scanner match >0)
You can use combination of add and forloop counter to achieve what you want to achieve. But remember you need to pass some variable (I've used rank here for kinda storing the increment variable in template.
views.py
rank = 0
return render(request, "base.html", {"items": items, "rank": rank})
html
{% for each_item in items %}
{% if each_item.scanner_count > 0 and each_item.scanner_match > 0 %}
{% if forloop.counter|add:rank <= 5 %}
<tr><td>{{each_item.threat_name}}</td></tr>
<br>
{% else %}
{% if forloop.last %}
<p><b><i> {{ forloop.counter|add:"-5" }} rows were truncated. See full report for more details. </i></b></p>
{% endif %}
{% endif %}
{% endif %}
{% endfor %}
As other commenters have noted, you cannot make an assignment of the forloop.counter in the template, as that would be considered logic that should be in the view (controller). Remove the {% else forloop.counter -= 1 %} from your code and it should work as I think you intended. If not, either add logic in the object (context) being passed to the template or user other forloop attributes/variables as found in the Django documentation here: https://docs.djangoproject.com/en/3.0/ref/templates/builtins/#for
I got this simple HTML template:
{% block html_page %}
{% set counter = 1 %}
{% for field in fields %}
COUNTER: {{ counter }} <br>
{% set counter = counter+1 %}
{% endfor %}
{% endblock %}
Where fieldscontains 4 items.
The output is:
COUNTER: 1
COUNTER: 1
COUNTER: 1
COUNTER: 1
While the output i want should be with the counter increasing:
COUNTER: 1
COUNTER: 2
COUNTER: 3
COUNTER: 4
The counter assignment is being done INSIDE the for loop, so I don't get why does it keep returning to 1.
Any suggestions?
This doesn't work due to scoping rules in Jinja.
After Jinja 2.10, to solve the scope problem, you can do something like this:
{% set count = namespace(a=0) %}
{% for field in fields %}
{{ count.a }}
{% set count.a = count.a + 1 %}
{% endfor %}
Or you could use loop.index:
{% for field in fields %}
{{ loop.index }}
{% endfor %}
I need to do a counter increment within a loop. I had a look at django for.counter, but unfortunately, my increments dont exactly occur within each iteration of the loop. So is there any way at all that I can implement increment of a variable within django template, without going to great pains to implement a new object in my code to do this without such an increment?
In the following code, I am writing the lines {{ count = 0 }}, {{ count += 1 }} just for illustration purpose. I know it wont work. The following is a very simplified form of my template:
<div class="jumbotron slotgroup slotavailable mb-1 mt-5" id="jumbo_week_avail">
<div class="slot-header" role="alert">
Headertext
</div>
{% if weeklyslotsav %}
{% for day,daynum in weekzip %}
{{ count = 0 }}
{% if daynum in weeklyslotsav.day %}
{% for weekslotav in weeklyslotsav %}
{% if weekslotav.day == daynum %}
<div class="row row_week_avail{{ weekslotav.day }}" id="row_week_avail{{ weekslotav.day }}_{{ count }}">
</div>
{{ count += 1 }}
{% endif}
{% endfor %}
{% else %}
<div class="row row_week_avail{{ daynum }}" id="row_week_avail{{ daynum }}_0">
</div>
{% endif %}
{% endfor %}
{% else %}
{% for weekday, weeknum in weekzip %}
<div class="row row_week_avail{{ weeknum }}" id="row_week_avail{{ weeknum }}_0">
</div>
{% endfor %}
{% endif %}
</div>
The following is a segment from my views:
def edit_doctorslots(request, cliniclabel, doctor_id):
doctor_id=int(doctor_id)
doc = get_object_or_404(doctor, docid=doctor_id)
cl = Clinic.objects.get(label=cliniclabel)
print("Clinic name", cl.name)
regularslotsav = ''
try:
regularslotsav = Timeslots.objects.filter(clinic =cl, doctor =doc, available =True)
except:
pass
regularslotsbr = ''
try:
regularslotsbr = Timeslots.objects.filter(clinic =cl, doctor =doc, available =False)
except:
pass
weekavzip = ''
try:
weeklyslotsav = Weekdays.objects.filter(clinic =cl, doctor =doc, available =True)
weekav = range(0, len(weeklyslotsav))
weekavzip = list(zip(weeklyslotsav, weekav))
except:
pass
weeklyslotsbr = ''
try:
weeklyslotsbr = Weekdays.objects.filter(clinic =cl, doctor =doc, available =False)
except:
pass
formslot = SlotForm()
formspecialdays = SpecialdaysForm()
formweekdays = WeekdaysForm()
weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
weekdaynum = [0,1,2,3,4,5,6]
weekzip = list(zip(weekdays, weekdaynum))
newweekzip = weekzip
return render(request, 'clinic/editslots0.html', {'rnd_num': randomnumber(), 'clinic': cl, 'doctor': doc, 'formslot': formslot, 'formspecialdays': formspecialdays, 'formweekdays': formweekdays, 'weekzip': weekzip, 'newweekzip': newweekzip, 'regav': regularslotsav, 'regbr': regularslotsbr, 'weekav': weekavzip, 'weekbr': weeklyslotsbr, 'weeklyslotsav': weeklyslotsav })
I've seen many similiar questions on SO. However in all of them I've seen people introducing for.counter. But this is not suitable for my purpose.
You can use with tag to set variables in template as -
{% with count=0 %}
{{ count}}
...do other stuffs
{% endwith %}
and for maths you could use django math filters like
{{ count|add:"1" }}
You can code you with use of both.
For more about setting variable in django template - How to set a value of a variable inside a template code?
and for using math in django - How to do math in a Django template?
Hope this helps you.
I am currently trying to fix an issue by using jinja variables, but somehow the variable does not keep the value outside the loop, even though I declared it before the loop begins:
{% set disablecounter = 0 %}
{% if disablecounter == 0 %}
{% for einzelroom in all_einzelzimmer %}
{% if zimmer.id == einzelroom.zimmer_id %}
{% set price = einzelroom.preis %}
<div class="preis-element">
<p class="preis"> <span class="smallab"> ab </span> {{ price|int }}€ </p>
</div>
{% set disablecounter = disablecounter + 1 %}
{{ disablecounter }}
{% endif %}
{% endfor %}
{% endif %}
{{ disablecounter }}
The variable is disablecounter inside the loop it is 1 but outside it is still 0
Thanks!
EDIT
Surrounding with a with statement also didnt worked:
{% with foo = 42 %}
{{ foo }}
{% endwith %}
{% with %}
{% set foo = 42 %}
{{ foo }}
{% endwith %}
I found a great solution here on SO by #Chris Warth.
Original answer by #Peter Hollingsworth:
https://stackoverflow.com/a/32700975/5291566
{% with disablecounter = [0] %}
{% if disablecounter == [0] %}
{% for einzelroom in all_einzelzimmer %}
{% if zimmer.id == einzelroom.zimmer_id %}
<div class="preis-element">
<p class="preis"> <span class="smallab"> ab </span> {{ einzelroom.preis|int }}€ </p>
</div>
{% if disablecounter.append(disablecounter.pop() + 1) %}{% endif %}
{% endif %}
{% endfor %}
{% endif %}
How to convert negative number to positive number in django template?
{% for balance in balances %}
{{ balance.amount }}
{% endfor %}
If balance.amount is negative number, I want to convert it to positive number.
I would like to suggest installing django-mathfilters.
Then you can simply use the abs filter like this:
{% for balance in balances %}
{{ balance.amount|abs }}
{% endfor %}
If you don't want/can't install django-mathfilters
You can make a custom filter quite easily:
from django import template
register = template.Library()
#register.filter(name='abs')
def abs_filter(value):
return abs(value)
This works without adding django-mathfilters but it's not a very good practice.
{% if balance.amount < 0 %}
{% widthratio balance.amount 1 -1 %}
{% else %}
{{ balance.amount }}
{% endif %}
Widthratio is meant for creating bar charts but can be used for multiplication
from this SO:
{% if qty > 0 %}
Please, sell {{ qty }} products.
{% elif qty < 0 %}
Please, buy {{ qty|slice:"1:" }} products.
{% endif %}