7

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

Right now I get this error:

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>

...
5
  • If bikesProfit is an dict passed to the context with the format {2012:10.0, 2011:13.0} then bikesProfit.year should work. Are you perhaps mixing str and int keys for year? Commented Nov 14, 2012 at 10:16
  • Also usable: stackoverflow.com/questions/1700661/… Commented Nov 14, 2012 at 10:17
  • What do bikesProfit and years_list look like when you pass them to the context? Commented Nov 14, 2012 at 10:22
  • Have you tried that RickyA? It seems to me that it shouldn't work since the key is not year, but the actual year (2000). Commented Nov 14, 2012 at 10:23
  • Trying now and indeed not working. It does bikesProfit["year"]. Bah. Commented Nov 14, 2012 at 10:53

3 Answers 3

21

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 }}
Sign up to request clarification or add additional context in comments.

2 Comments

@goliney as this is the first answer on google, you might consider placing the : behind the function header! Aaaand I`m out...
@user2033511 thank you, on my way to editing the answer
3

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>
    ...

Comments

2

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)) 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.