我如何写一个数字循环在Django模板?我的意思是
for i = 1 to n
我如何写一个数字循环在Django模板?我的意思是
for i = 1 to n
当前回答
为了防止其他人遇到这个问题,我创建了一个模板标签,可以创建一个范围(…):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
其他回答
你可以通过:
{'n':范围(n)}
使用模板:
{% for I in n %} ... {% endfor %}
你不传递n本身,而是传递range(n)[包含从0到n-1的整数列表],从你的视图到你的模板,在后者中,你在range %}中为i执行{%(如果你绝对坚持以1为基础,而不是正常的以0为基础的索引,你可以使用forloop。循环体中的计数器;-)。
的绑定
{'n' : range(n) }
到模板,然后做
{% for i in n %}
...
{% endfor %}
注意,您将得到基于0的行为(0,1,…)n - 1)。
(为兼容Python3而更新)
我使用了一种简单的技术,可以很好地处理没有特殊标记和附加上下文的小情况。有时这很有用
{% for i in '0123456789'|make_list %}
{{ forloop.counter }}
{% endfor %}
{% with ''|center:n as range %}
{% for _ in range %}
{{ forloop.counter }}
{% endfor %}
{% endwith %}