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

后端 未结 3 1026
情话喂你
情话喂你 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:10

    I don't think this is directly possible (edit: you can manually implement it with filters, as shown in goliney's answer). The documentation says:

    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.

    If your case is not more complicated than what you're showing, the best solution in my opinion would be to loop over bikeProfit instead.

    {% for year, profit in bikeProfit.items %}
        ...
        <th>Total profit {{ year }}:</th>
        ...
        <th> {{ profit }} </th>
        ...
    
    0 讨论(0)
  • 2020-12-18 10:16

    It's possible, but goes against the grain of the Django model...

    If you have items of interest, then ideally your view should return an object just containing those items, (OTTOMH something like):

    Something.objects.filter(something__typename='Bike', year__range=(1998, 2001)) 
    
    0 讨论(0)
  • 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 }}
    
    0 讨论(0)
提交回复
热议问题