2011-02-02 54 views
1

我是新來的django,拼命想弄清楚爲什麼我不能得到一套字典對象來呈現。這裏是模板的片段 - 一些pprints進行調試:爲什麼django不喜歡我的字典?

<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應該產生該對象列表。我不確定我錯過了什麼。

回答

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 }} 
+0

很好的清潔解決方案! @alex如果你是django的新手,它可能會幫助你知道把代碼放在哪裏 - 查看http://docs.djangoproject.com/en/1.2/howto/custom-template-tags/ – meshantz 2011-02-02 17:34:07