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

for i = 1 to n

当前回答

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

其他回答

显示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 %}

不幸的是,Django模板语言不支持这一点。有一些建议,但它们看起来有点复杂。我只要在上下文中放一个变量:

...
render_to_response('foo.html', {..., 'range': range(10), ...}, ...)
...

在模板中:

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

为了防止其他人遇到这个问题,我创建了一个模板标签,可以创建一个范围(…):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

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

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

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