nested loopin of a dictionary of lists of dictionary of lists in django template

28 Views Asked by At

I have a data structure data as below which is passed in to the template. I want to iterate through that to get the values to be displayed in an HTML table like below

data = {
        'section1_header': [
        {
            'r1_name': ['u1', 'u2', 'u3',]},
        {
            'r2_name': ['v1', 'v2', 'v3',]},
    ],
        'section2_header': [
        {
            'R1_name': ['U1', 'U2', 'U3']},
        {
            'R2_name': ['V1', 'V2', 'V3']}
    ],}

display format:

section1_header
    r1_name   |  u1  | u2  |u3
    r2_name   |  v1  | v2  |v3
section2_header
    R1_name   | U1   | U2  |U3
    R2_name   | V1   | V2  |V3

I have applied the nested loops to access the values

{% for section,row_items in data.items() %}
  <tr>
 <td>  {{section}} </td>
  </tr>
    {% for row_values in row_items %}
     <tr>
        {% for rowname,value_list in row_values.items() %}
        <td>{{rowname}}</td
           {% for value in value_list %}
            <td>{{value}}</td>
           {% endfor %}
        {%endfor%}
        </tr>
    {% endfor %}
{% endfor %}

Upon rendering it is not printing the values other than the section. Any fix for this? If possible, without using templatetags.

1

There are 1 best solutions below

0
Scraps23 On

The looping logic is fine, so I think the error is in the template that your rendering. Adapting from this answer, try the template below:

td {
  border-left: 0;
  border-top: 0;
  border-bottom: 0;
  border-right: 0;
}

table {
  border: none;
  border-collapse: collapse;
}

.grouplabel {
  background: blue;
  color: yellow;
  border: 1px solid blue;
  border-radius: 5px;
}
<table>
        <thead>
                <tr>
                        <th>Item</th>
                        <th>Attr 1</th>
                        <th>Attr 2</th>
                        <th>Attr 3</th>
                </tr>
        </thead>
        {% for section, rows in data.items() %}
        <tbody id="{{ section.lower() }}">
                <tr class="grouplabel"><th colspan="4">
                        {{ section.upper() }}
                </th></tr>
                {% for row_data in rows %}
                <tr>
                        {% for title, details in row_data.items() %}
                        <th>{{ title }}</th>
                        <td>{{ details[0] }}</td>
                        <td>{{ details[1] }}</td>
                        <td>{{ details[2] }}</td>
                        {% endfor %}
                </tr>
                {% endfor %}
        </tbody>
        {% endfor %}
</table>

Running this code produced the below output. Of course, change the styling as you need it: enter image description here