[Django]-How to loop 7 times in the django templates

50👍

views.py:

context['loop_times'] = range(1, 8)

html:

{% for i in loop_times %}
        <option value={{ i }}>{{ i }}</option>
{% endfor %}

55👍

In python strings are iterables so this works :

{% for i in "1234567" %}
    <option value={{i}}> {{i}}</option>
{% endfor %}

It’s explicit, so quite OK, but zjm1126’s answer is probably better for long term consideration.

0👍

Django templates don’t support ranges. You have a couple options:

  1. Add a range filter: http://djangosnippets.org/snippets/1357/

Here’s how you add custom filters: http://docs.djangoproject.com/en/dev/howto/custom-template-tags/

  1. Use a different templating system, like Mako, that does support it.

http://docs.djangoproject.com/en/dev/ref/templates/api/#using-an-alternative-template-language
Django-Mako is a shortcut project for using Mako: http://code.google.com/p/django-mako/

👤Jordan

Leave a comment