How To Do A Forloop In A Django Template?
Solution 1:
The Django template language has For loops. See:
https://docs.djangoproject.com/en/dev/ref/templates/builtins/#for
....you might notice that there is no clear shot at the kind of "repeat" functionality you're after. You can, for example, define an int in your view (i in your case) and pass its range into the template context, and then iterate through the range of that int (of course, in Python, int objects themselves are not iterable).
However, the more 'pythonic' approach is to be explicit: Ask yourself, "Why do I want to iterate ten times?" Is that the number of coconuts being displayed on this page about the brave swallow who carried them? If so, don't iterate through the number 10 - instead iterate directly through the list of coconut objects and do your presentation logic right there in the forloop.
{% for coconut in coconuts %}
hello, {{forloop.counter}} {# Something useful about the coconut goes here. #}
{% endfor %}
Assuming there are ten coconuts, this will produce the same result as your example. However, as I point out in my comment, you can surely do something more useful with the coconut object once inside the loop.
If you really, absolutely feel that you need to loop through a static range without passing it in from your business logic, you may find this snippet useful:
http://djangosnippets.org/snippets/1899/
Again, I'd caution you to make sure that you are doing what you really want to do and not merely cementing over a deeper crack in your knowledge management.
Solution 2:
You could use a custom filter to do that easily:
from django.template import Library
register = Library()
@register.filterdefrange(value):
return xrange(value)
Then in your template:
{% for i in 10|range %}
hello <br/>
{% endfor %}
Solution 3:
This can be achieved by implementing your own template tag to repeat certain blocks. Have a look at the official documentation at https://docs.djangoproject.com/en/dev/howto/custom-template-tags/
That way you can use it by writing:
{% repeat 3 %}
<div>htmlto repeat</div>
{% endrepeat %}
This is an old snippet from 2009 which does the above, it might need updating to work with Django 1.3 though, but should be enough to get you started: http://djangosnippets.org/snippets/1499/
Post a Comment for "How To Do A Forloop In A Django Template?"