I have multiple lists created in python. I am trying to convert these lists into HTML rows.
week = ['1','2']
date = ['2022-10-01','2022-10-09']
My HTML table should look like below:
Week Date
1 2022-10-01
2 2022-10-09
what I tried so far:
{% for val in data %}
<tr>
<td>
{% for item in val.week %} {{ item }} <br> {% endfor %}
</td>
<td>
{% for item in val.date %} {{ item }} <br> {% endfor %}
</td>
</tr>
{% endfor %}
The problem with above code is every value is treated as cell instead of row and hence I am unable to apply any row related styles to the above.
Could someone help with how to convert these to rows instead of cells.
Thank you.
CodePudding user response:
You can use dictionary comprehension to convert the two lists into a dictionary where the key would be the week number and the value would be the corresponding date. You can loop over the dictionary as key and value using the items attribute in the template.
# views.py
week = [1, 2]
date = ['2022-10-01','2022-10-09']
data = {week[i]: date[i] for i in range(len(week))}
return render(request, 'template.html', {'data': data})
# template.html
{% for key, value in data.items %}
<tr>
<td> {{ key }} </td>
<td> {{ value }} </td>
</tr>
{% endfor %}
CodePudding user response:
try this approch...
------ views.py ------
week = ['1','2']
date = ['2022-10-01','2022-10-09']
data = tuple(zip(week,date))
------ html ------
<table style="border: 1px solid; border-collapse: collapse;">
<thead>
<th>Weeks</th>
<th>Dates</th>
</thead>
<tbody>
<tbody>
{% for i,j in data %}
<tr>
<td>{{i}}</td>
<td>{{j}}</td>
</tr>
{% endfor %}
</tbody>
</tbody>
</table>