美文网首页
Django for 循环,forloop:实际用于题目编号

Django for 循环,forloop:实际用于题目编号

作者: 西多的大叔 | 来源:发表于2017-07-25 21:18 被阅读0次

    在django的模板中,有forloop这一模板变量,颇似PHPSmarty中的foreach.customers,

    Smarty foreach如下:

    {foreach name=customers from=$custid item=curr_id}

    {$smarty.foreach.customers.iteration} <-- Tells you which item you are at (integer)

    {$smarty.foreach.customers.first} <-- Tells you if the current item is the first item (boolean)

    {$smarty.foreach.customers.last} <-- Tells you if the current item is the last item (boolean)

    {$smarty.foreach.customers.total} <-- Tells you how many items are in the array (integer)

    {/foreach}

    而django forloop如下:

    在每个`` {% for %}``循环里有一个称为`` forloop`` 的模板变量。这个变量有一些提示循环进度信息的属性。

    forloop.counter 总是一个表示当前循环的执行次数的整数计数器。 这个计数器是从1开始的,所以在第一次循环时 forloop.counter 将会被设置为1。

    {% for item in todo_list %}

    {{ forloop.counter }}: {{ item }}

    {% endfor %}

    forloop.counter0 类似于 forloop.counter ,但是它是从0计数的。 第一次执行循环时这个变量会被设置为0。

    forloop.revcounter 是表示循环中剩余项的整型变量。 在循环初次执行时 forloop.revcounter 将被设置为序列中项的总数。 最后一次循环执行中,这个变量将被置1。

    forloop.revcounter0 类似于 forloop.revcounter ,但它以0做为结束索引。在第一次执行循环时,该变量会被置为序列的项的个数减1。

    forloop.first 是一个布尔值,如果该迭代是第一次执行,那么它被置为```` 在下面的情形中这个变量是很有用的:

    System Message: WARNING/2 (, line 1071); backlink

    Inline literal start-string without end-string.

    {% for object in objects %}

    {% if forloop.first %}

  1. {% else %}
  2. {% endif %}
  3. {{ object }}

    {% endfor %}

    forloop.last 是一个布尔值;在最后一次执行循环时被置为True。 一个常见的用法是在一系列的链接之间放置管道符(|)

    {% for link in links %}{{ link }}{% if not forloop.last %} | {% endif %}{% endfor %}

    上面的模板可能会产生如下的结果:

    Link1 | Link2 | Link3 | Link4

    另一个常见的用途是为列表的每个单词的加上逗号。

    Favorite places:

    {% for p in places %}{{ p }}{% if not forloop.last %}, {% endif %}{% endfor %}

    forloop.parentloop 是一个指向当前循环的上一级循环的 forloop 对象的引用(在嵌套循环的情况下)。 例子在此:

    {% for country in countries %}

    {% for city in country.city_list %}

    Country #{{ forloop.parentloop.counter }}

    City #{{ forloop.counter }}

    {{ city }}

    {% endfor %}

    {% endfor %}

    forloop 变量仅仅能够在循环中使用。 在模板解析器碰到{% endfor %}标签后,forloop就不可访问了。

    Context和forloop变量

    在一个 {% for %} 块中,已存在的变量会被移除,以避免 forloop 变量被覆盖。 Django会把这个变量移动到 forloop.parentloop 中。通常我们不用担心这个问题,但是一旦我们在模板中定义了 forloop 这个变量(当然我们反对这样做),在 {% for %} 块中它会在 forloop.parentloop 被重新命名。

    相关文章

      网友评论

          本文标题:Django for 循环,forloop:实际用于题目编号

          本文链接:https://www.haomeiwen.com/subject/phpgkxtx.html