0

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']
keydict={'keys':keys}

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

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

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

{'firstkey':'firstkey'}

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:

views.py

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

template

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

Which produces this result:

image

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

Adam Jaamour
  • 1,326
  • 1
  • 15
  • 31
Marcus Grass
  • 1,043
  • 2
  • 17
  • 38
  • Possible duplicate of [Django - Calling list or dict item using a variable in template](https://stackoverflow.com/questions/49875924/django-calling-list-or-dict-item-using-a-variable-in-template) – Adam Jaamour Apr 17 '18 at 15:37
  • Yeah, that was me, I realized the problem was more general, calling a dict or list with a variable was unrelated to the loop, so I reformulated my question to be more on point! – Marcus Grass Apr 17 '18 at 19:52

0 Answers0