2012-11-14 57 views
4

如何在django模板中使用變量作爲索引?如何在django模板中使用變量作爲索引?

現在我得到這個錯誤:

Exception Type: 
TemplateSyntaxError 

Exception Value:  
Could not parse the remainder: '[year]' from 'bikesProfit.[year]' 

我也試過{{ bikesProfit.year }}但是這給空的結果。

{% for year in years_list %} 

     <tr> 
      <th>Total profit {{ year }}:</th> 
     </tr> 
     <tr> 
      <th></th> 
      <th> {{ bikesProfit[year] }} </th> 

... 
+0

如果bikesProfit是一個格式爲「{2012:10.0,2011:13.0}」的字典,那麼'bikesProfit.year'應該可以工作。你可能在一年中混合使用'str'和'int'鍵嗎? – RickyA

+0

也可用:http://stackoverflow.com/questions/1700661/access-array-elements-in-a-django-template – RickyA

+0

當你將它們傳遞給上下文時,'bikesProfit'和'years_list'看起來像什麼? – RickyA

回答

8

這是一個很常見的問題,SO上有很多答案。

您可以custom template filter

@register.filter 
def return_item(l, i): 
    try: 
     return l[i] 
    except: 
     return None 

用法:

{{ bikesProfit|return_item:year }} 
+0

這個答案適合我。非常感謝您的回覆。 – janb

+0

@goliney,因爲這是谷歌的第一個答案,你可以考慮將':'放在函數頭後面! Aaaand我出來了... – enpenax

+0

@ user2033511謝謝你,在我編輯答案的方式 –

2

我不認爲這是可能的直接(編輯:你可以手動過濾器實現它,如圖goliney's answer) 。該documentation說:

Because Django intentionally limits the amount of logic processing available in the template language, it is not possible to pass arguments to method calls accessed from within templates. Data should be calculated in views, then passed to templates for display.

如果你的情況是不是比你出什麼更復雜的,在我看來,最好的辦法是遍歷bikeProfit代替。

{% for year, profit in bikeProfit.items %} 
    ... 
    <th>Total profit {{ year }}:</th> 
    ... 
    <th> {{ profit }} </th> 
    ... 
+0

+1是我的下一個建議:) – RickyA

1

這是可能的,但違背Django的模型的穀物...

如果你有感興趣的項目,那麼最好你的觀點應該只返回包含這些項目,(OTTOMH類似的對象):

Something.objects.filter(something__typename='Bike', year__range=(1998, 2001)) 
相關問題