How to use a variable as an index in a django template?

How to use a variable as an index in a django template?

I am getting this error now:

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

I also tried {{ bikesProfit.year }} , but this gives an empty result.

  {% for year in years_list %} <tr> <th>Total profit {{ year }}:</th> </tr> <tr> <th></th> <th> {{ bikesProfit[year] }} </th> ... 
+4
source share
3 answers

This is a very common question, there are many answers to SO.

You can make a custom template filter :

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

Using:

 {{ bikesProfit|return_item:year }} 
+11
source

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

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

If your case is not more complicated than what you are showing, the best solution in my opinion would be to bikeProfit .

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

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

If you have objects of interest, then ideally your view should return an object containing only these elements (OTTOMH something like):

 Something.objects.filter(something__typename='Bike', year__range=(1998, 2001)) 
+1
source

Source: https://habr.com/ru/post/1445969/


All Articles