Back to index

plone3  3.1.7
createMultiColumnList.py
Go to the documentation of this file.
00001 ## Script (Python) "createMultiColumnList"
00002 ##bind container=container
00003 ##bind context=context
00004 ##bind namespace=
00005 ##bind script=script
00006 ##bind subpath=traverse_subpath
00007 ##parameters=input_list,numCols=3, sort_on=None
00008 ##title=Turn a single list into a list of lists for multi column display
00009 """ This method turns a list into a list of sublists for multi-column display.
00010     The number of sublists is determined by the numCols parameter.  The
00011     initial list may optionally be sorted based on the sort_on property, which
00012     should be the name of a property or method on the list items or the string
00013     'self', which will cause the list to be sorted in place without a sort
00014     function.
00015 """
00016 
00017 list_len = len(input_list)
00018 
00019 if sort_on and sort_on != 'self':
00020     # function for generating sort attribute (if callable)
00021     get_sort_attr = lambda x: (callable(getattr(x, sort_on, None)) and
00022                            getattr(x, sort_on)() or getattr(x, sort_on, None))
00023 
00024     dec_list = [(get_sort_attr(l), l) for l in input_list]
00025     dec_list.sort()
00026     input_list = [l[1] for l in dec_list]
00027 elif sort_on == 'self':
00028     input_list.sort()
00029 
00030 # Calculate the length of the sublists
00031 sublist_len = (list_len % numCols == 0 and list_len / numCols or
00032                                                     list_len / numCols + 1)
00033 
00034 # Calculate the list end point given the list number
00035 list_end = lambda list_num: (list_num == numCols - 1 and list_len or
00036                              (list_num+1)*sublist_len)
00037 
00038 # Generate columns
00039 final_lists = [input_list[i*sublist_len:list_end(i)] for i in range(numCols)]
00040 
00041 return final_lists