Reputation: 1874
I have a list of names. From django view.py function i am rendering it on UI.
names=[a,b,c,d,e,f,g,h...]
return render(request, 'show_names_list.html', names)
On UI i want to show it as
Names
a d g
b e h
c f
My show_names_list.html looks like:
<span>Names</span>
<div class="mr-l15">
{%for item in names%}
<span>{{item}} </span>
{% endfor %}
It gives me:
a b c d e f
g h i j
Can anyone please help with the html part, where i can get the names in correct format.
Upvotes: 1
Views: 132
Reputation: 931
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>
Upvotes: 1
Reputation: 11606
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 %}
Upvotes: 1