0

I'm trying to call a dictionary or list object in a template using a variable in that template with no results.

What I'm trying to is identical to this general python code:

keylist=[
        'firstkey',
        'secondkey',
        'thirdkey',
        ]
exampledict={'firstkey':'firstval',
             'secondkey':'secondval',
             'thirdkey':'thirdval',
             }

for key in keylist:
    print(exampledict[key])

#Produces:
    #firstval
    #secondval
    #thirdval

Things work a little different in the django template. I have a variable defined as key='firstkey' passed onto the template. If i want to call the same dictionary:

{{ exampledict.firstkey }} #Produces: firstval
{{ exampledict.key }} #Produces: None

Django template for loops also has a produced variable forloop.counter0, increasing from 0 in the firstloop to n-1 in the last loop, this cannot call list objects. I have a list:

tabletitles=['first table', 'second table', 'third table']

And I want to call and create tables in a loop, putting the table titles for the respective tables above like so:

{% for table in tables %}
<h3> first table </h3>
<table>
...
</table>
{% endfor %}

What I would like to do in this case is

{% for table in tables %}
<h3> {{ tabletitles.forloop.counter0 }} </h3>
<table>
...
</table>
{% endfor %}

Which doesn't work either, since I can't use a separate variable to call an object for a dict or list in the template. Is there a way to get this to work, or a better way to do it all together?

Marcus Grass
  • 1,043
  • 2
  • 17
  • 38

1 Answers1

3

The Django template language does not let you access dictionary keys and lists with variables. You could write a template tag to do this (see this question for example), but in your case there's a simpler alternative.

In your view, zip your tables and titles together

tables_and_titles = zip(tables, tabletiles)

Then loop through them together in your template.

{% for table, title in tables_and_titles %}
    {{ title }}
    <table>
    {{ table }}
    </table>
{% endfor %}
Alasdair
  • 298,606
  • 55
  • 578
  • 516