我如何写一个数字循环在Django模板?我的意思是
for i = 1 to n
我如何写一个数字循环在Django模板?我的意思是
for i = 1 to n
当前回答
的绑定
{'n' : range(n) }
到模板,然后做
{% for i in n %}
...
{% endfor %}
注意,您将得到基于0的行为(0,1,…)n - 1)。
(为兼容Python3而更新)
其他回答
如果数字来自一个模型,我发现这是一个很好的模型补丁:
def iterableQuantity(self):
return range(self.quantity)
此方法支持标准range([start,] stop[, step])函数的所有功能
< >应用templatetags /太阳城. py
from django import template
register = template.Library()
@register.filter(name='range')
def _range(_min, args=None):
_max, _step = None, None
if args:
if not isinstance(args, int):
_max, _step = map(int, args.split(','))
else:
_max = args
args = filter(None, (_min, _max, _step))
return range(*args)
用法:
{% load range %}
<p>stop 5
{% for value in 5|range %}
{{ value }}
{% endfor %}
</p>
<p>start 5 stop 10
{% for value in 5|range:10 %}
{{ value }}
{% endfor %}
</p>
<p>start 5 stop 10 step 2
{% for value in 5|range:"10,2" %}
{{ value }}
{% endfor %}
</p>
输出
<p>stop 5
0 1 2 3 4
</p>
<p>start 5 stop 10
5 6 7 8 9
</p>
<p>start 5 stop 10 step 2
5 7 9
</p>
你应该在模板中使用“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>
对于那些寻找简单答案的人来说,只需要显示一个数值的数量,比如从100个帖子中添加3个,例如添加{% For post in posts|slice:"3" %}并正常循环,只会添加3个帖子。
为了防止其他人遇到这个问题,我创建了一个模板标签,可以创建一个范围(…):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