How can I use a variable as index in django template?

后端 未结 3 1030
情话喂你
情话喂你 2020-12-18 09:45

How can I use a variable as index in django template?

Right now I get this error:

Exception Type:
TemplateSyntaxError

Exception Value:    
Could not         


        
3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-18 10:22

    It's a very common question, there are a lot of answers on SO.

    You can make custom template filter:

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

    Usage:

    {{ bikesProfit|return_item:year }}
    

提交回复
热议问题