2015-12-03 105 views
4

自定義計數器我有這樣的代碼在Django模板頁面在Django模板

<select class="selectpicker datatable-column-control" multiple 
{% for q_group in question_groups %} 
    <optgroup label="{{ q_group.name }}"> 
    {% for q in q_group.questions %} 
     <option value="{{ forloop.counter0 }}">{{ q.title }}</option> 
    {% endfor %} 
    </optgroup> 
{% endfor %} 

我要爲每一個選項標籤,增加在每次迭代中值。如果我有10個選項標記,那麼它們的值將從0到9. forloop.counter0不滿足我的需要,因爲當外循環完成一次時內循環計數器初始化爲0。

回答

1

如何將itertools.count對象傳遞給模板?

模板:

<select class="selectpicker datatable-column-control" multiple> 
{% for q_group in question_groups %} 
    <optgroup label="{{ q_group.name }}"> 
    {% for q in q_group.questions %} 
     <option value="{{ counter }}">{{ q.title }}</option> 
    {% endfor %} 
    </optgroup> 
{% endfor %} 
</select> 

查看:

import itertools 
import functools 

render(request, 'template.html', { 
    question_groups: ..., 
    counter: functools.partial(next, itertools.count()), 
}) 
+0

https://asciinema.org/a/al1ctm3wwwgf5ey0lfpin10yr – falsetru

0

回想起這個帖子提供僅使用模板語言解決方案。

如果您知道在計數器之間只有一個{% for %}(如上例所示),請使用forloop.parentloop。您可以將許多這些鏈接在一起,但是分離所需循環的循環數量必須是已知的,並且在幾個(forloop.parentloop.parentloop...)之後使用它變得不太理想。

{% for foo in foos %} 
    {% for bar in bars %} {# exactly one for loop between here #} 
    {{ forloop.parentloop.counter0 }} is the index of foo. 
    {% endfor %} 
{% endfor %} 

如果你有兩個循環之間(比如在模板中,你無法控制,或者Django的脆皮形式)的任意數,節省了with statement循環變量:

{% for foo in foos %} 
    {% with foo_num=forloop.counter0 %} 
    {% for bar in bars %} {# any number of for loops between #} 
     {{ foo_num }} is the index of foo. 
    {% endfor %} 
    {% endwith %} 
{% endfor %} 

Falsetru的解決方案是最適合缺少for循環的計數器,或者是在一個循環結束後繼續計數的計數器。這個特性對於只有內建函數來說是不可能的,所以來自這個函數的itertools是必要的。

{% for foo in foos %} 
    {{ counter }} is the index of foo 
{% endfor %} 
{% for bar in bars %} 
    {{ counter }} is the index of bar + len(foos) 
{% endfor %}