Reputation: 818
I want to render a table look like this:
<table>
<tr>
<td>some data</td>
<th>special one</th>
<td>some data</td>
...
<td>some data</td>
</tr>
...
</table>
There is a solution that can render all in the same tag.
<table>
{% for rowval in results %}
<tr>
{% for val in rowval %}
<td>{{val}}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
But in my case, there would be a th
at the second place for every row of the data, if there is a record.
There is another solution that not as good as the answer below as it keeps partial table, td
and tr
in the view.
Is there a way to implement this feature?
Upvotes: 0
Views: 84
Reputation: 32294
There are some variables available inside a django template for loop, one of them is named forloop.counter
which gives you the current iteration of the loop. You can use this variable to render something differently on the second loop
<table>
{% for rowval in results %}
<tr>
{% for val in rowval %}
{% if forloop.counter == 2 %}
<th>{{ val }}</th>
{% else %}
<td>{{ val }}</td>
{% endif %}
{% endfor %}
</tr>
{% endfor %}
</table>
Upvotes: 1