【发布时间】:2018-11-02 07:58:01
【问题描述】:
如何在 Django 模板中遍历并显示字典“索引名”或“键名”?以下是上下文中的字典。
基本上这是我的字典all_options[category][sub_category][name] 的结构。 “类别、子类别和名称”是动态的。我想先显示“类别”,然后向下钻取到“子类别”,然后再向下钻取。
模板不允许使用方括号来访问 dict 属性。
提前致谢!
上下文
'Condenser (WC)': {
'Water Box': {
'2MPA Condenser Water Box': {
'option': '2MPA Condenser Water Box',
'chillers': [{
'chiller': 'xxxxxxxxxxx',
'factory': '2' ,
'option': 'WB240.2U.F2HVKA>
}, {
'chiller': 'xxxxxxxxxxx',
'factory': '1' ,
'option': 'WB088.2H.F2AYFA>
}]
},
},
'Anodes': {
'Magnesium Anodes': {
'option': 'Magnesium Anodes',
'chillers': [{
'chiller': 'xxxxxxxxxxx',
'factory': '2' ,
'option': 'WB240.2U.F2HVKA>
}, {
'chiller': 'xxxxxxxxxxx',
'factory': '2' ,
'option': 'WB240.2U.F2HVKA>
}]
}
},
'Stainless Steel Tube Sheet': {
'304 SS Condenser Tube Sheets': {
'option': '304 SS Condenser Tube Sheets',
'chillers': [{
'chiller': 'xxxxxxxxxxx',
'factory': '2' ,
'option': 'WB240.2U.F2HVKA>
}]
},
}
},
模板
在模板中,我添加了一个注释,它是需要打印的字符串。
{% for category_name in all_options %}
{{ category_name }} #Condenser (WC)
{% for subcat in category_name %}
{{ subcat }} #Water Box
{% for item in subcat %}
{{ item }} #2MPA Condenser Marine Water Box
{% for chiller in item.chillers %}
{{ chiller.option }} #WB200.3K.F2HVKA
{% endfor%}
{% endfor%}
{% endfor%}
{% endfor %}
【问题讨论】: