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

for i = 1 to n

当前回答

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

{% for i in '0123456789'|make_list %}
    {{ forloop.counter }}
{% 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>

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

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

你可以通过:

{'n':范围(n)}

使用模板:

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

对于那些寻找简单答案的人来说,只需要显示一个数值的数量,比如从100个帖子中添加3个,例如添加{% For post in posts|slice:"3" %}并正常循环,只会添加3个帖子。

我对这个问题的看法,我认为是最蟒蛇的。在你的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 %}