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

for i = 1 to n

当前回答

显示1到20个数字:

{% for i in "x"|rjust:"20"|make_list %}
 {{ forloop.counter }}
{% endfor %}

这也可以帮助你: (count_all_slider_objects来自视图)

{% for i in "x"|rjust:count_all_slider_objects %}
  {{ forloop.counter }}
{% endfor %}

or

  {% with counter=count_all_slider_objects %}
    {% if list_all_slider_objects %}
      {%  for slide in list_all_slider_objects %}
        {{forloop.counter|add:"-1"}}
        {% endfor%}
      {% endif %}
    {% endwith %}

其他回答

你不传递n本身,而是传递range(n)[包含从0到n-1的整数列表],从你的视图到你的模板,在后者中,你在range %}中为i执行{%(如果你绝对坚持以1为基础,而不是正常的以0为基础的索引,你可以使用forloop。循环体中的计数器;-)。

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

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

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

显示1到20个数字:

{% for i in "x"|rjust:"20"|make_list %}
 {{ forloop.counter }}
{% endfor %}

这也可以帮助你: (count_all_slider_objects来自视图)

{% for i in "x"|rjust:count_all_slider_objects %}
  {{ forloop.counter }}
{% endfor %}

or

  {% with counter=count_all_slider_objects %}
    {% if list_all_slider_objects %}
      {%  for slide in list_all_slider_objects %}
        {{forloop.counter|add:"-1"}}
        {% endfor%}
      {% endif %}
    {% endwith %}
{% for i in range(10) %}
   {{ i }}

{% endfor %}