Home Django - Looping through a dictionary using a second variable in template
Reply: 0

Django - Looping through a dictionary using a second variable in template

user2367 Published in April 25, 2018, 6:07 pm

I'm trying my best not to repeat myself in my code but I'm encountering a problem looping through a dictionary by key in my template.

I have two dicts:

exampledict={'firstkey':firstval, 'secondkey':secondval}

keys=['firstkey', 'secondkey']

In my template I want to loop over the exampledict using the keydict:

{% for val in keydict %}
<td>{{ exampledict.val }}</td>
{% endfor %}

I've noticed this kind of combination of variables doesn't work at all, I tried by using:


And sending that through to the template and later trying

{{ exampledict.firstkey }}

Is there a better way to accomplish what I'm trying to do here?

Edit 1:

Manually going through each key as:

<td> {{ exampledict.firstkey }} </td> <td> {{ exampledict.secondkey }} </td>

Where firstkey and secondkey is the actual dictkey for exampledict works, although it makes for a lot of repetition.

Edit 2:


def tabletest(request):
    exampledict={'firstkey':'firstval', 'secondkey': 'secondval'}
        'keys':['firstkey', 'secondkey']
    return render(request, 'MinaFakturor/tabletest.html', {'exampledict':exampledict, 'keydict':keydict})


                {% for val in keydict.keys %}
                <th>{{ val }}</th>
                {% endfor %}
                {% for val in keydict.keys %}
                <td>{{ exampledict.val }}</td>
                {% endfor %}
                <td>{{ exampledict.firstkey }}</td>

Which produces this result:

If I remove the exampledict.firstkey term, nothing is produced in the table body.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.301461 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO