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

for i = 1 to n

当前回答

{% for _ in ''|center:13 %}
    {{ forloop.counter }}
{% 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

你可以在views.py的上下文中传递range(n)而不是n。这将给你一个可迭代的列表。

context['range']= range(n)

然后你可以这样迭代你的模板:

{% for i in range %}
   <!-- your code -->
{% endfor %}

你应该在模板中使用“slice”,一个这样的例子:

在views.py

contexts = {
    'ALL_STORES': Store.objects.all(),
}

return render_to_response('store_list.html', contexts, RequestContext(request, processors=[custom_processor]))

在store_list.html:

<ul>
{% for store in ALL_STORES|slice:":10" %}
    <li class="store_item">{{ store.name }}</li>
{% endfor %}
</ul>

的绑定

{'n' : range(n) }

到模板,然后做

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

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

(为兼容Python3而更新)

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