2011-12-02 88 views
0

我有一本字典:循環通過列表在Django模板

babies = {'clothes list':['a','b','c','d'], 'lots of toys': 'yes'} 

現在在模板我想做的相當於:

for cloth in babies['clothes list']: 
    print cloth 

我已經過濾key_lookup定義。所以做這個工作模板:

{{ babies|key_lookup:'lots of toys' }} 

但這樣做

{% for cloth in babies|key_lookup:'clothes list' %} 

不起作用。

上述字典僅僅是一個例子。我無法修改字典鍵。 key_lookup被定義爲

def key_lookup(the_dict, key): 
    return the_dict.get(key, None) 

回答

1

您在使用with試過嗎?如果這只是一個語法問題,這可能會起作用:

{% with clothes=babies|key_lookup:'clothes list' %} 
    {% for cloth in clothes %} 
     ... 
    {% endfor %} 
{% endwith %} 
+0

這應該是'衣服像嬰兒一樣......'嗎? – Ben

+0

nrabinowitz該works..thanks。 Django模板你爲什麼這麼難? – ghostcoder

+0

@Ben - 我認爲上面在Django 1.3加入的語法 - 見[該文檔(https://docs.djangoproject.com/en/1.3/ref/templates/builtins/#with)。較舊的語法仍然支持,但我認爲你有它向後:'有嬰兒| ...作爲clothes' – nrabinowitz