Search code examples
dictionaryjinja2show

How to access dictionary value in jinja? Is it possible or not? If possible then how?


I'm trying to use this code snippet in a Django project.
How can I access each key's value (the list)?
And show the list items?

I want to display a table like this using Jinja. Is it possible?

key values
100 1,2
200 3,4
300 5,6
400 7,8

There can be thousands of rows in the table.

def index(request):

    data = {
        100: [{'childId': 1, 'childStructure': 'Leaf'}, {'childId': 2, 'childStructure': 'Intermediate'}],
        200: [{'childId': 3, 'childStructure': 'Intermediate'}, {'childId': 4, 'childStructure': 'Leaf'}],
        300: [{'childId': 5, 'childStructure': 'Leaf'}, {'childId': 6, 'childStructure': 'Intermediate'}],
        400: [{'childId': 7, 'childStructure': 'Intermediate'}, {'childId': 8, 'childStructure': 'Leaf'}],
    }

    return render(request,'index.html', {'data': data})

Solution

  • You can use a for to loop on dictionaries. You just have to use dict.items() to do so, as pointed in the documentation.

    Given the template:

    <table style="border: 1px solid">
      <tr>
        <th>key</th>
        <th>value</th>
      </tr>
    {% for key, value in data.items %}
      <tr>
        <td>{{ key }}</td>
        <td>{{ value | map(attribute='childId') | join(',') }}</td>
      </tr>
    {% endfor %}
    </table>
    

    This would give you:

    <table>
      <tr>
        <th>key</th>
        <th>value</th>
      </tr>
      <tr>
        <td>100</td>
        <td>1,2</td>
      </tr>
      <tr>
        <td>200</td>
        <td>3,4</td>
      </tr>
      <tr>
        <td>300</td>
        <td>5,6</td>
      </tr>
      <tr>
        <td>400</td>
        <td>7,8</td>
      </tr>
    </table>