2010-11-15 19 views
0

如何增加模板中變量的值.. ??Django加法

{% 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

http://mywiki.wooledge.org/XyProblem – 2010-11-15 17:00:40

+0

如果您知道如何增加模板中某個變量的值,那麼請讓我知道.. !! – 2010-11-15 17:11:32

回答

4

如果你想增加i在所有嵌套的循環,你可以通過另一種狀態上下文變量,如i=itertools.count(),並且在模板中,您使用

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

Django documentation on the template language design狀態模板語言的理念是

的模板系統是爲了表達表示,而不是程序邏輯。

而這通常意味着你不能直接用過濾器操縱狀態。要實現狀態更改,您必須創建自己的狀態變量,其狀態可以通過函數調用進行更改。

+0

我不明白它將如何工作 – 2010-11-15 18:40:32

+0

哦..我明白了 非常感謝:) – 2010-11-15 18:43:34

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 %} 
+0

但是,第二個循環再次運行,然後我會再次在第三個循環中獲得相同的值。 – 2010-11-15 17:29:31

+0

嗯...看着使用嵌套forloop計數器。 – crodjer 2010-11-15 17:31:04

+0

在getid參數中傳遞如答案更新中的forloop計數器的總和。 – crodjer 2010-11-15 17:46:07

0
+0

這隻會返回值的添加,但不會更改變量的值。 – 2010-11-15 17:24:41

+0

這隻會改變輸出。它不會改變變量'i'的值。 – 2010-11-15 17:25:34

+0

你可以試試這個:http://stackoverflow.com/questions/2376511/how-to-access-outermost-forloop-counter-with-nested-for-loops-in-django-templates訪問父循環計數器和使用添加標籤根據外層更新最內層的循環。 – crodjer 2010-11-15 17:33:34