2

I have a three column table (columns 1 & 3 will show an image). I am looping over the object list in the template with a forloop.

Within the loop I want to force the forloop to go to the next item so the item in the 3rd column is the next record. I can't see anything like 'forloop.next' in the django docs.

{% for item in object_list %}<tr>
    <td><a href="{{ item.url }}"><img src="{{ MEDIA_URL }}{{ item.image }}" width="300" height="100" /></a></td>
    <td>&nbsp;</td>
    <td><a href="{{ item.url }}"><img src="{{ MEDIA_URL }}{{ item.image }}" width="300" height="100" /></a></td>
</tr>
{% endfor %}<tr>

What's the best way to accomplish this?

zio
  • 2,145
  • 4
  • 21
  • 25

1 Answers1

2

You can make iterator, that will produce a pair of elements on every iteration.

Something like

from itertools import tee, izip, islice

iter1, iter2 = tee(object_list)
object_list = izip(islice(iter1, 0, None, 2), islice(iter2, 1, None, 2))

# if object_list == [1,2,3,4,5,6,7,8] then result will be iterator with data: [(1, 2), (3, 4), (5, 6), (7, 8)]

Or you can do the trick in template:

{% for item in object_list %}
{% if forloop.counter0|divisibleby:2 %}
<tr>
<td><a href="{{ item.url }}"><img src="{{ MEDIA_URL }}{{ item.image }}" width="300" height="100" /></a></td>
<td>&nbsp;</td>
{% else %}
<td><a href="{{ item.url }}"><img src="{{ MEDIA_URL }}{{ item.image }}" width="300" height="100" /></a></td>
</tr>
{% endif %}
{% endfor %}

But make sure there are even elements in your set, or <tr> won't be closed.

DrTyrsa
  • 31,014
  • 7
  • 86
  • 86