Reputation: 9163
I have a list:
c = [1,2,3,4,5,6,7,8]
in my template, I want to output this as follows:
<table>
<tr>
<td>1</td>
<td>2</td>
<td>...</td>
</tr>
</table>
<table>
<tr>
<td>5</td>
<td>...</td>
<td>8</td>
</tr>
</table>
What is the best way to do this?
Upvotes: 1
Views: 53
Reputation: 665
If you'd like to make it more generic, you can also use the built in divisibleby
tag
{% for value in c %}
{% if forloop.counter0|divisibleby:cut_off %}
<table>
<tr>
{% endif %}
<td>{{value}}</td>
{% if forloop.counter|divisibleby:cut_off %}
</tr>
</table>
{% endif %}
{% endfor %}
where c
is the list and cut_off
is the slicing number (e.g. 4 in your question). These variables are supposed to be sent the to the template in your view.
Upvotes: 2
Reputation: 473873
You can use slice
template filter:
<table>
<tr>
{% for value in c|slice:":4" %}
<td>{{ value }}</td>
{% endfor %}
</tr>
</table>
<table>
<tr>
{% for value in c|slice:"4:" %}
<td>{{ value }}</td>
{% endfor %}
</tr>
</table>
Assuming c
is passed in the template context.
slice
basically follows usual python slicing syntax:
>>> c = [1,2,3,4,5,6,7,8]
>>> c[:4]
[1, 2, 3, 4]
>>> c[4:]
[5, 6, 7, 8]
Upvotes: 1