django另外

时间:2010-11-15 16:59:16

标签: django django-templates

如何增加模板中变量的值.. ??

{% for s in list%}
     {% for subject in s%}
             {% for sub in subject %}

                    <div id="{{ sub| getid:i }}"></div> 
                    # here i want to increment the value of i 
             {% endfor %}
      {% endfor %}
{% endfor %}

3 个答案:

答案 0 :(得分:4)

如果要在所有嵌套循环上增加i,可以传递另一个有状态上下文变量,例如i=itertools.count(),并在模板中使用

<div id="{{ sub| getid:i.next }}"></div>

Django documentation on the template language design表示模板语言的哲学是

  

模板系统用于表达表示,而不是程序逻辑。

这通常意味着您无法直接使用过滤器操纵状态。要实现状态更改,您必须创建自己的有状态变量,其状态可以通过函数调用进行更改。

答案 1 :(得分:3)

使用模板进行循环?您可以尝试使用:

  

forloop.counter

请参阅此处的文档:http://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs

实现:

{% for s in list%} 
  {% for subject in s%} 
    {% for sub in subject %}
                <div id="{{ sub| getid:forloop.counter+(forloop.parentloop.counter - 1)*total_iterations_inner_loop+(forloop.parentloop.parentloop.counter-1)*total_iterations_mid_loop*total_iterations_inner_loop }}"></div> 
         {% endfor %}
  {% endfor %}
{% endfor %}

答案 2 :(得分:0)