[Django]-Django template for loop iterating two item

8👍

If you can control the list structure that is cList, why don’t you just make it a list of tuples of 2 elements or a list of list of 2 elements, like

#in the view
cList = [(ob1, ob2), 
         (ob3, ob4)]

and the in the template

{% for c1, c2 in cList %}

 <ul class="ListTable">
   <li>
     {{ c1.name }}
   </li>
   <li>
      {{ c2.name }}
   </li>
</ul>
 {% endfor %}

Also you can use the zip function to facilitate the creation of cList, or define a
function which create that kind of structure from a list of objects, like

def pack(_list):
    new_list = zip(_list[::2], _list[1::2])
    if len(_list) % 2:
        new_list.append((_list[-1], None))
    return new_list

4👍

One option is to use the the built-in template tag cycle

and do something like:

{% for c in c_list %}
    {% cycle True False as row silent %}

    {% if row %}
        <ul class="ListTable">
    {% endif %}

        <li>
             {{ c.name }}
        </li>

    {% if not row or forloop.last %}
        </ul>    
    {% endif %}

{% endfor %}

Note: if you have odd number of element on the list the last table will have only one element with this option, sice we are checking for forloop.last

👤Rafen

1👍

I tried to implement cyraxjoe solution which does work, but theres only one problem with it…

a = [1,2,3] will return [(1,2)] but will remove the 3.

So i was asking around in irc freenode #python for a solution and i got this:

it = iter(a); nested = [list(b) for b in itertools.izip_longest(it, it)]
print nested
[[1, 2], [3, None]]

I was also told to look up the documentation for the itertools module, and search for the “grouper” recipe. which does something similar but i havent tried it yet.

I hope this helps 🙂

*Credits to except and lvh from the #python channel

👤Agey

Leave a comment