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

for i = 1 to n

当前回答

你可以使用: {% with " |center: I as range %}

其他回答

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

你甚至可以访问idx!

views.py:

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

html:

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

我对这个问题的看法,我认为是最蟒蛇的。在你的apps templatetags目录中创建一个my_filters.py。

@register.filter(name='times') 
def times(number):
    return range(number)

在模板中的用法:

{% load my_filters %}
{% for i in 15|times %}
    <li>Item</li>
{% 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

你可以通过:

{'n':范围(n)}

使用模板:

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

{% with ''|center:n as range %}
{% for _ in range %}
    {{ forloop.counter }}
{% endfor %}
{% endwith %}