开发者

How to do a forloop in a Django template?

I know how to do a forloop to 开发者_如何学编程get the objects from a list but here I'm talking about a forloop in order to repeat something a certain number of times. Like how in PHP I would do:

for (i=0; i < 10; i++) {

   hello <br />

}

This would output hello 10 times. So how to do this in django template language?


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.


You could use a custom filter to do that easily:

from django.template import Library
register = Library()

@register.filter
def range(value):
    return xrange(value)

Then in your template:

{% for i in 10|range %}
    hello <br/>
{% endfor %}


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>html to 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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜