我是django的新手,并拼命想弄清楚为什么我无法获取一组字典对象来呈现。这是模板的片段 - 有一些用于调试的pprints:
<ul>
{% with req.requirement_id as reqid %}
req.requirement_id: {{ req.requirement_id|pprint }}<br />
reqid: {{ reqid|pprint }}<br />
e_quals: {{ e_quals|pprint }}<br />
e_quals.reqid: {{ e_quals.reqid|pprint }}<br />
{% for qual in e_quals.reqid %}
qual.qual_type: {{ qual.qual_type }}
{% if qual.qual_type == "self" %}
<li>Only self-endorsements.</li>
{% endif %}
{% if qual.qual_type == "other" %}
<li>No self-endoresements.</li>
{% endif %}
{% if qual.qual_type == "hasa" %}
<li>Endorser must hold an active {{ qual.qual_data }} badge.</li>
{% endif %}
{% endfor %}
{% endwith %}
</ul>
以下是我得到的结果:
req.requirement_id: u'man_keephead'
reqid: u'man_keephead'
e_quals: {u'man_keephead': [<EndorsementQual: man_keephead_others>, <EndorsementQual: man_keephead_man>], u'man_trustself': [<EndorsementQual: man_trustself_self>], u'man_waiting': [<EndorsementQual: man_waiting_other>]}
e_quals.reqid: ''
我真的好像 - 鉴于reqid和e_quals字典,e_quals.reqid应该生成该对象列表。我不确定我错过了什么。
答案 0 :(得分:2)
你不能在Django的模板语言中做这种间接变量解析。它始终将e_quals.req_id
解释为e_quals["req_id"]
- 即作为文字键。
您需要创建一个简单的模板过滤器:
@register.filter
def dict_get(my_dict, key):
return my_dict.get(key)
{{ e_quals|dict_get:req_id }}