[英]django template syntax to iterate through two lists
我有以下django模板,當我迭代列表( class_list_overall
)時,我想使用forloop.counter0
作為另一個列表中的索引( classTimeSlots
)。 它只是給我一個TemplateSyntaxError
。 我嘗試了以下變化:
{{classTimeSlots.{{forloop.counter0}}}}
{{classTimeSlots.[forloop.counter0]}}
{{classTimeSlots.{forloop.counter0}}}
{{classTimeSlots.(forloop.counter0)}}
{{classTimeSlots.forloop.counter0}}
{% with forloop.counter0 as index%} <legend>{{ classTimeSlots.index}}</legend> {% endwith %}
這些都沒有奏效。 有什么建議么? 我只是DJango的新手。 我正在使用Google App Engine。
這是代碼片段(我知道它效率低但我一直在嘗試不同的東西):
{% for class_list in class_list_overall %}
<fieldset> <legend>{{ classTimeSlots.forloop.counter0 }}</legend>
<ul>
<li> <label>First Choice </label>
<select class="dropdown" name="class{{forloop.counter}}1" size="1">
<option value="Click Here to Choose" selected="selected">Click Here to Choose</option>
{% for class in class_list %}
<option>{{class}}</option>
{% endfor %}
</select>
</li>
<li>
<label>Second Choice </label>
<select class="dropdown" name="class{{forloop.counter}}2" size="1">
<option value="Click Here to Choose" selected="selected">Click Here to Choose</option>
{% for class in class_list %}
<option>{{class}}</option>
{% endfor %}
</select>
</li>
</ul>
</fieldset>
{% endfor %}
簡短的回答:你做不到。
模板語言不會嘗試確定以點語法傳遞的變量的值。
它將對forloop.counter0
進行文字查找
1:編寫一個接受變量和鍵的模板標簽,並讓它返回variable[key]
2:這很可能在視圖中完成。 我可以看嗎?
Django不支持這一點 - 它是故意限制的。 相反,您應該修改視圖函數以將兩個列表zip
在一起,並將其傳遞給模板。
它可能但不值得推薦:
{% for class_list in class_list_overall %}
<fieldset> <legend>
{% for cts in classTimeSlots %}
{% ifequal forloop.counter forloop.parentloop.counter %} {{cts}}
{% endifequal %}
{% endfor %} </legend>
<ul>
<li> <label>First Choice </label>
<select class="dropdown" name="class{{forloop.counter}}1" size="1">
<option value="Click Here to Choose" selected="selected">Click Here to Choose</option>
{% for class in class_list %}
<option>{{class}}</option>
{% endfor %}
</select>
</li>
<li>
<label>Second Choice </label>
<select class="dropdown" name="class{{forloop.counter}}2" size="1">
<option value="Click Here to Choose" selected="selected">Click Here to Choose</option>
{% for class in class_list %}
<option>{{class}}</option>
{% endfor %}
</select>
</li>
</ul>
</fieldset>{% endfor %}
但最好將列表納入父詞典:
[class_list_overall[i].update({'label':classTimeSlots[i]}) for i in range(0,len(classTimeSlots))]
然后將上面的代碼更改為:
<legend>
{{ class_list.label }}
</legend>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.