2011-02-16 48 views
0

這是我的views.py:爲什麼我的Django的模板不能顯示當前的事情

a=['aaa','bbb','oooo','qqqq','gggg'] 

def main(request, template_name='index.html'): 
    context ={ 
       'n':range(len(a)), 
       'a':a, 
    } 
    return render_to_response(template_name, context) 

這是我的html:

{% for i in n %} 

    {{a.i}} ww {{a.i+1}} 

{% endfor %} 

它表明ww ww ww ww ww

,但我想顯示'aaawwbbb bbbwwoooo oooowwqqqq qqqqwwgggg ggggww'

所以我能做什麼,

謝謝

回答

0

您可以創建一個自定義過濾器,http://docs.djangoproject.com/en/1.2/howto/custom-template-tags/和有這樣的事情:

# myfilters.py 
def return_element(list, index): 
    return list[index+1] 

然後你就可以在模板中使用它,

{% include myfilters %} 
... 
{% for i in a %} 
    {{ i }}ww{{ a|return_element:forloop.counter0 }} 
{% endfor %} 

forloop模板變量自動設置爲for標籤.. forloop.counter0返回循環輸入的次數,並使用零索引。

0

不要這樣做。直接在列表中迭代。

context = { 
    'a': a 
} 
return render_to_response(template_name, context) 

而且在模板:

{% for x in a %} 
    {{ x }} 
{% endfor %} 
+0

但是,我想告訴A.I + 1 – zjm1126 2011-02-16 08:48:39

1
>>> c=Context({'a':['aaa', 'bbb', 'oooo', 'qqqq', 'gggg']}) 
>>> Template("{% for x in a %}{% if not forloop.first %}{{ x }} {% endif %}{{ x }}ww{% endfor %}").render(c) 
u'aaawwbbb bbbwwoooo oooowwqqqq qqqqwwgggg ggggww' 
相關問題