Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django template for loop iterating two item

I try to implement a forloop in Django tempalte iterating two items per cycle such that

{% for c in cList%}
<ul class="ListTable">
    <li>
         {{ c1.name }}
    </li>
    <li>
         {{ c2.name }}
    </li>

</ul>
{% endfor %}

I know my code is not a proper way to do that but I couldn't find anyway. I really appreciate for any suggestion

Thanks

like image 993
brsbilgic Avatar asked Dec 29 '25 06:12

brsbilgic


2 Answers

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
like image 104
cyraxjoe Avatar answered Dec 31 '25 00:12

cyraxjoe


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

like image 43
Rafen Avatar answered Dec 30 '25 23:12

Rafen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!