[Answered ]-How to sort a list column wise on UI in django html

1๐Ÿ‘

โœ…

If you know how many items you want per column this template tag may be useful for splitting into vertical lists. This may work best in combination with bootstrap โ€“ using โ€œcol-md-2โ€, for example:

<div class="row">
<div class="col-md-2"><ul>
{% for item in names %}

{% if forloop.counter0|divisibleby:"3" %}
</ul></div>
<div  class="col-md-2"><ul>
{% endif %}

<li>{{ item }}</li>
{% endfor %}

</ul></div>
๐Ÿ‘คphilngo

1๐Ÿ‘

Re-grouping the items in the list can help.

In the view

from itertools import zip_longest

names=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
gr = [iter(names)]*3 # 3 is the number of rows
gb = zip(*zip_longest(*gr))
new_names = [ el for t in gb for el in t if el ]
return render(request, 'show_names_list.html', new_names)

Now names is

['a', 'd', 'g', 'j', 'b', 'e', 'h', 'c', 'f', 'i']

and you can try what happens in the template.

Alternatively, we can do:

in the view

from itertools import zip_longest

names=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
gr = [iter(names)]*3 # 3 is the number of rows
gb = zip(*zip_longest(*gr))
return render(request, 'show_names_list.html', gb)

and in the template

<span>Names</span>
<div class="mr-l15">
{%for row in names %}
 {%for item in row %}
    <span>{{ item|default:"" }} </span>
 {% endfor %}
 <br>
{% endfor %}
๐Ÿ‘คPynchia

Leave a comment