我如何写一个数字循环在Django模板?我的意思是
for i = 1 to n
我如何写一个数字循环在Django模板?我的意思是
for i = 1 to n
当前回答
你应该在模板中使用“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>
其他回答
{% for i in range(10) %}
{{ i }}
{% endfor %}
的绑定
{'n' : range(n) }
到模板,然后做
{% for i in n %}
...
{% endfor %}
注意,您将得到基于0的行为(0,1,…)n - 1)。
(为兼容Python3而更新)
你可以通过:
{'n':范围(n)}
使用模板:
{% for I in n %} ... {% endfor %}
如果数字来自一个模型,我发现这是一个很好的模型补丁:
def iterableQuantity(self):
return range(self.quantity)
你应该在模板中使用“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>