我如何写一个数字循环在Django模板?我的意思是
for i = 1 to n
我如何写一个数字循环在Django模板?我的意思是
for i = 1 to n
当前回答
也许像这样?
{% for i in "x"|rjust:"100" %}
...
{% endfor %}
其他回答
这需要一个范围函数。Django的一个特性票被提出了(https://code.djangoproject.com/ticket/13088),但关闭为“不会修复”以下的评论。
我对这个想法的印象是,它试图导致在模板中编程。如果您有一个需要呈现的选项列表,那么它们应该在视图中计算,而不是在模板中。如果这就像一个值范围那么简单,那就这样吧。
他们有一个很好的观点——模板应该是视图的非常简单的表示。您应该在视图中创建有限的必需数据,并将其传递给上下文中的模板。
为了防止其他人遇到这个问题,我创建了一个模板标签,可以创建一个范围(…):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
我只是把流行的答案做得更深入一些,让它更健壮。这允许您指定任何起点,例如0或1。它还使用了python的range特性,其中末尾少了一个,因此可以直接与列表长度一起使用。
@register.filter(name='range')
def filter_range(start, end):
return range(start, end)
然后在你的模板中只包括上面的模板标签文件,并使用以下:
{% load myapp_filters %}
{% for c in 1|range:6 %}
{{ c }}
{% endfor %}
现在你可以用1-6代替0-6或者硬编码。添加一个步骤将需要一个模板标签,这应该涵盖更多的用例,所以这是向前迈出的一步。
你可以通过:
{'n':范围(n)}
使用模板:
{% for I in n %} ... {% endfor %}
{% with ''|center:n as range %}
{% for _ in range %}
{{ forloop.counter }}
{% endfor %}
{% endwith %}