List divide columns across

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
from django.template import Library

register = Library()

@register.filter
def columnsacross(list, n):
	"""
	Divide list into (n) of columns going across
	
	Example:
	{% for column in object_list %}
	<ul>
		{% for item in column %}
			<li>{{ item }}</li>
		{% endfor %}
	</ul>
	{% endfor %}
		
	>>> list = range(1, 11)
	>>> columnsacross(list, 4)
	[[1, 5, 9], [2, 6, 10], [3, 7], [4, 8]]
	>>> columnsacross(list, 3)
	[[1, 4, 7, 10], [2, 5, 8], [3, 6, 9]]
	"""
	try:
		n = int(n)
	list = list(list)
		except (ValueError, TypeError):
		return [list]
        
	return [list[i::n] for i in range(n)]
	
if __name__ == "__main__":
    import doctest
    doctest.testmod()

More like this

  1. Template filter that divides a list into exact columns by davmuz 2 years, 2 months ago
  2. CheckboxSelectMultiple that renders in columns by rfugger 3 years, 6 months ago
  3. Template tag: split list to n sublists by movielady 5 years, 9 months ago
  4. StringListField (database field) by guettli 4 years, 11 months ago
  5. partition template filters by SmileyChris 6 years, 7 months ago

Comments

(Forgotten your password?)