在從詞典中檢索值迭代我有一個映射目標查詢上下文字典項objectives
反對屬於該目標的測試列表。示例代碼:「的」報表應使用「在Y X」的格式:同時使用Django模板
objectives = Objective.objects.filter(requirement=requirement)
context_dict["requirements"][requirement] = objectives
for objective in objectives:
tests = Test.objects.filter(objective=objective)
context_dict["objectives"][objective] = tests
在我的django html模板中,我遍歷目標並顯示它們。然後我想迭代屬於這些目標的測試。當我這樣做:
{% for test in {{ objectives|get_item:objective }} %}
我得到一個TemplateSyntaxError: 'for' statements should use the format 'for x in y':
在應用/ templatetags目錄,我有:
from django.template.defaulttags import register
...
@register.filter
def get_item(dictionary, key):
return dictionary.get(key)
相反,如果我做{{ objectives|get_item:objective }}
一個JS變量,我看到它確實產生了一個列表,我應該能夠迭代。當然,我不能混用JS變量和Django模板標籤,所以這是僅用於調試:
var tests = {{ objectives|get_item:objective }}
var tests = [<Test: AT399_8_1>, <Test: AT399_8_2>, <Test: AT399_8_3>, <Test: AT399_8_4>, <Test: AT399_8_5> '...(remaining elements truncated)...']
如何遍歷這個列表中的Django模板標籤?
問題是你不能在{%...%}標籤裏面使用{{...}}語法。用等效的Python代碼替換「{{targets | get_item:objective}}」。 – Bakuriu
@Bakuriu你不能做內部'{%...%}'標籤的字典訪問,但 - 相當於Python代碼是'目標[目的]',這是行不通的。 –
@JeremyWeirich字典在django模板中的訪問使用'''運算符。 '{{dictionary.key}}'輸出值,但它不適用於你,因爲密鑰不能是一個變量 –