• django模板之forloop


    在django的模板中,有forloop这一模板变量,颇似php Smarty中的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 %}
            <p>{{ forloop.counter }}: {{ item }}</p>
        {% endfor %}
    forloop.counter0 类似于 forloop.counter ,但是它是从0计数的。 第一次执行循环时这个变量会被设置为0。
    forloop.revcounter 是表示循环中剩余项的整型变量。 在循环初次执行时 forloop.revcounter 将被设置为序列中项的总数。 最后一次循环执行中,这个变量将被置1。
    forloop.revcounter0 类似于 forloop.revcounter ,但它以0做为结束索引。在第一次执行循环时,该变量会被置为序列的项的个数减1。
    forloop.first 是一个布尔值,如果该迭代是第一次执行,那么它被置为```` 在下面的情形中这个变量是很有用的:
    System Message: WARNING/2 (<string>, line 1071); backlink
    Inline literal start-string without end-string.
        {% for object in objects %}
            {% if forloop.first %}<li class="first">{% else %}<li>{% endif %}
            {{ object }}
            </li>
        {% 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 %}
            <table>
            {% for city in country.city_list %}
            <tr>
            <td>Country #{{ forloop.parentloop.counter }}</td>
            <td>City #{{ forloop.counter }}</td>
            <td>{{ city }}</td>
            </tr>
            {% endfor %}
            </table>
        {% endfor %}
    forloop 变量仅仅能够在循环中使用。 在模板解析器碰到{% endfor %}标签后,forloop就不可访问了。

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

    转自:http://blog.csdn.net/cain/article/details/6623717

  • 相关阅读:
    MyEclipse 2015 SVN 安装
    PL/SQL中查询Oracle大数(17位以上)时显示科学计数法的解决方法
    Oracle密码过期the password has expired
    解决telnet无法连接 Connection refused
    提示-bash: telnet: command not found的解决方法
    ORACLE WITH AS 用法
    Oracle创建Database Link
    oracle操作字符串:拼接、替换、截取、查找、长度、判断
    Java Web 清除缓存
    mount 命令用法
  • 原文地址:https://www.cnblogs.com/liuxiaowei/p/7769333.html
Copyright © 2020-2023  润新知