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?

1 Answer 1

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

1 Comment

Took me a while to get back to it, absolutely solved the issue implemented exactly as described, thanks!

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.