我如何写一个数字循环在Django模板?我的意思是

for i = 1 to n

当前回答

我在这个问题上很努力,我找到了最好的答案: (来自如何在django模板中循环7次)

你甚至可以访问idx!

views.py:

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

html:

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

其他回答

我只是把流行的答案做得更深入一些,让它更健壮。这允许您指定任何起点,例如0或1。它还使用了python的range特性,其中末尾少了一个,因此可以直接与列表长度一起使用。

@register.filter(name='range')
def filter_range(start, end):
    return range(start, end)

然后在你的模板中只包括上面的模板标签文件,并使用以下:

{% load myapp_filters %}

{% for c in 1|range:6 %}
    {{ c }}
{% endfor %}

现在你可以用1-6代替0-6或者硬编码。添加一个步骤将需要一个模板标签,这应该涵盖更多的用例,所以这是向前迈出的一步。

的绑定

{'n' : range(n) }

到模板,然后做

{% for i in n %}
...
{% endfor %}

注意,您将得到基于0的行为(0,1,…)n - 1)。

(为兼容Python3而更新)

我在这个问题上很努力,我找到了最好的答案: (来自如何在django模板中循环7次)

你甚至可以访问idx!

views.py:

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

html:

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

为了防止其他人遇到这个问题,我创建了一个模板标签,可以创建一个范围(…):http://www.djangosnippets.org/snippets/1926/

Accepts the same arguments as the 'range' builtin and creates a list containing
the result of 'range'.

Syntax:
    {% mkrange [start,] stop[, step] as context_name %}

For example:
    {% mkrange 5 10 2 as some_range %}
    {% for i in some_range %}
      {{ i }}: Something I want to repeat\n
    {% endfor %}

Produces:
    5: Something I want to repeat 
    7: Something I want to repeat 
    9: Something I want to repeat

我使用了一种简单的技术,可以很好地处理没有特殊标记和附加上下文的小情况。有时这很有用

{% for i in '0123456789'|make_list %}
    {{ forloop.counter }}
{% endfor %}