Reputation: 73
My Django view is returning a list of dictionaries. This goes to html table through template rendering. Below is my template code,
My list of dictionary looks like below,
Results :
[{ 'name':'x','age': 20}, {'name': 'y','age': 25 }]
<table class="table table-striped" border="1" class="dataframe">
<thead>
<tr style="text-align: center;">
{% for k, v in results.0.items %}
<th>{{ k }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for x in results %}
<tr style="text-align: center;">
{% for y in x %}
<td> {{ x.y }} </td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
Expected output:
name age
x 20
y 25
But the output is blank.
Please let me know if there is anything wrong with my HTML table template.
Upvotes: 0
Views: 336
Reputation: 2974
You can use items
properly in your inner loop just like the outer loop
<div>
<table class="table table-striped" border="1" class="dataframe">
<thead>
<tr style="text-align: center;">
{% for k, v in results.0.items %}
<th>{{ k }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for x in results %}
<tr style="text-align: center;">
{% for i,j in x.items %}
<td> {{ j }} </td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
</div>
Upvotes: 1