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

for i = 1 to n

当前回答

的绑定

{'n' : range(n) }

到模板,然后做

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

注意,您将得到基于0的行为(0,1,…)n - 1)。

(为兼容Python3而更新)

其他回答

也许像这样?

{% for i in "x"|rjust:"100" %}
...
{% 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 %}

的绑定

{'n' : range(n) }

到模板,然后做

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

注意,您将得到基于0的行为(0,1,…)n - 1)。

(为兼容Python3而更新)

{% for _ in ''|center:13 %}
    {{ forloop.counter }}
{% endfor %}

我在这个问题上很努力,我找到了最好的答案: (来自如何在django模板中循环7次)

你甚至可以访问idx!

views.py:

context['loop_times'] = range(1, 8)

html:

{% for i in loop_times %}
        <option value={{ i }}>{{ i }}</option>
{% endfor %}