21π
Check out the documentation on the for
loop.
It automatically creates a variable called forloop.counter
that holds the current iteration index.
As far as the greater question on how to declare variables, there is no out-of-the-box way of doing this with Django, and it is not considered a missing feature but a feature. If you really wanted to do this it is possible with custom tags but for the most part the philosophy you want to follow is that mostly anything you want to do that would require this should be done in the view and the template should be reserved for very simple logic. For your example of summing up a total, for example, you could use the add filter. Likewise, you can create your own filters just like with tags.
6π
If you want to set any variable inside a Django template, you can use this small template tag Iβve written.
- Add confirmation step to custom Django management/manage.py command
- How do I extend the Django "login" form?
- IntegrityError: distinguish between unique constraint and not null violations
- Django Grappelli Tabular Inline add new row TinyMCE textfield not editable
3π
this is how to do it:
{% with name="World" greeting="Hello" %}
<html>
<div>{{ greeting }} {{name}}!</div>
</html>
{% endwith %}
see also: with tag
by john and yarden from this post:
How to set a value of a variable inside a template code?
- Django: instance needs to have a primary key value before a many-to-many relationship
- 'CheckoutView' object has no attribute 'object'
- How to upload and read csv file in django using csv.DictReader?
- Django haystack highlight template tag issue
2π
In template:
{% for outer_obj in outer_list %}
{% for inner_obj in inner_list %}
{% increment_counter forloop.counter0 forloop.parentloop.counter0 outer_list.count %}
{% endfor %}
{% endfor %}
Templatetag:
@register.simple_tag
def increment_counter(outer, inner, outer_loop_length):
return outer + inner * outer_loop_length + inner * (outer_loop_length - 1)
Result: 0 1 2 3 β¦