[Twisted-web] Nevow - how to render sequence into 3 column table

Samuel Reynolds sam at SpinwardStars.com
Wed Dec 7 10:58:07 MST 2005


You'd need a custom renderer that does the
multicolumn layout.

I've attached a function that takes a list of items
and returns a list of lists. I created it for the
purpose you describe. It's not the prettiest or
most elegant code I've written, but I wrote it
when I was learning Python; since it works, and
I don't need it often, I haven't bothered trying
to improve it.

I added a couple of simple examples to the docstring.

Hope this helps.

- Sam

At 2005-12-07 06:17 PM +0100, you wrote:
>Leif K-Brooks wrote:
>>>The result should looks like:
>>>    <table>
>>>      <tr>
>>>        <td>Alfred is 15</td>
>>>        <td>Mary is 17</td>
>>>        <td>Bob is 25</td>
>>>      </tr>
>>>      ...
>>>      <tr>
>>>        <td>Molly is 22</td>
>>>        <td>Manfred is 33</td>
>>>      </tr>
>>>    </table>
>>If all you really want to do is have the names and ages displayed next
>>to each other, why not use ordinary nevow:render="sequence" along with
>>CSS? A demonstration of the stylesheet you'll need is at
>><http://tw.ecritters.biz/html_examples/tile/>.
>
>Thanks for this hint, it solve 50% of my needs ...
>There is one reason, why I'd like prefer the <table> solution:
>the variable column width!
>In real, I'd like to use this for database field editing and the variable
>field width get very important.
>
>But your way is better than no way !!!
>Paul
>
>_______________________________________________
>Twisted-web mailing list
>Twisted-web at twistedmatrix.com
>http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-web

__________________________________________________________
Spinward Stars, LLC                        Samuel Reynolds
Software Consulting and Development           303-805-1446
http://SpinwardStars.com/            sam at SpinwardStars.com 
-------------- next part --------------
#	PlaceInColumns.py
#
#	Code by Samuel Reynolds.
#	This code is hereby released to the public domain.
#

def PlaceInColumns( itemList, numColumns=2, flReadAcross=False, flReturnAsRows=False ):
	"""
	Group the items in itemList for multiple-column presentation.
	
	Examples:
	1.	To present data as a 4-column HTML table:
			rowData = PlaceInColumns( myData, 4, True, True )
			#                                    ^^^^  ^^^^
			print '<table>'
			for row in rowData:
				TDs = [ '<td>%s</td>' % elt for elt in row ]
				print '<tr>%s<tr>' % ''.join( TDs )
			print '</table>'
	
	2.	To present data as a 4-column HTML table
		using only one row (items separated vertically by linebreaks):
			colData = PlaceInColumns( myData, 4, True, False )
			#                                    ^^^^  ^^^^^
			print '<table>'
			print '<tr>'
			for col in colData:
				print '<td>'
				print '<br />'.join( col )
				print '</td>'
			print '</tr>'
			print '</table>'
		
	"""
	outList = []
	if numColumns < 2:
		outList.append( itemList )
	else:
		numItems = len( itemList )
		
		if flReadAcross:	# Read across the columns
			idx = 0
			numCopies = 0
			subList = []
			while numCopies < numItems:
				subList.append( itemList[idx] )
				numCopies += 1
				idx = idx + numColumns
				if idx >= numItems:
					outList.append( subList )
					subList= []
					idx = idx % numColumns + 1
			if len( subList ) > 0:
				outList.append( subList )
		else:	# Read down the columns
			def CalcItemsPerColumn( cols, count ):
				perCol = count / cols
				if cols * perCol < count:
					perCol += 1
				return perCol
			idx = 1
			numCopies = 0
			numColumnsRemaining = numColumns
			subList = []
			itemsPerColumn = CalcItemsPerColumn( numColumnsRemaining, numItems )
			while numCopies < numItems:
				subList.append( itemList[ numCopies ] )
				numCopies += 1
				idx = idx + 1
				if idx > itemsPerColumn:
					outList.append( subList )
					subList = []
					idx = 1
					numColumnsRemaining -= 1
					if numColumnsRemaining > 1:
						itemsPerColumn = CalcItemsPerColumn( numColumnsRemaining, numItems - numCopies )
					else:
						itemsPerColumn = numItems - numCopies
	
	if not flReturnAsRows:
		return outList
	
	#Rows requested
	numCols = len( outList )
	numRows = len( outList[0] )
	rowsList = []
	subList = []
	numCopies = 0
	rowIdx = 1
	colIdx = 1
	for rowIdx in range( 0, numRows ):
		subList = []
		for colIdx in range( 0, numCols ):
			try:
				subList.append( outList[colIdx][rowIdx] )
			except:
				None
		rowsList.append( subList )
	
	return rowsList


if __name__ == "__main__":
	
	def TEST( trial, expect, flIgnoreNewlines=False ):
		"""
		Run trial script, compare to expected result,
		and print pass or fail message.
		"""
		result = eval( trial )
		if flIgnoreNewlines:
			expect = string.replace( expect, "\n", "\r" )
			while expect[-1] == '\r':
				expect = expect[:-1]
			result = string.replace( result, "\n", "\r" )
			while result[-1] == '\r':
				result = result[:-1]
		if result == expect:
			print "[PASS]      ", trial
		else:
			print "[FAIL] **** ", trial
			print "=" * 75
			print "Expect:"
			print "." * 75
			print expect
			print "-" * 75
			print "\nResult:"
			print "." * 75
			print result
			print "=" * 75
	
	# PlaceInColumns
	itemList = ['a','b','c','d','e','f','g']
	
	expectList = [ itemList ]
	TEST( "PlaceInColumns( itemList, 1 )", expectList )
	
	expectList = [['a'],['b'],['c'],['d'],['e'],['f'],['g']]
	TEST( "PlaceInColumns( itemList, 1, flReturnAsRows=True )", expectList )
	
	expectList = [['a','b','c','d'],['e','f','g']]
	TEST( "PlaceInColumns( itemList, 2 )", expectList )
	
	expectList = [['a','c','e','g'], ['b','d','f']]
	TEST( "PlaceInColumns( itemList, 2, flReadAcross=True )", expectList )
	
	expectList = [['a','b','c'],['d','e'],['f','g']]
	TEST( "PlaceInColumns( itemList, 3 )", expectList )
	
	expectList = [['a','d','f'],['b','e','g'],['c']]
	TEST( "PlaceInColumns( itemList, 3, flReturnAsRows=True )", expectList )
	
	expectList = [['a','d','g'],['b','e'],['c','f']]
	TEST( "PlaceInColumns( itemList, 3, flReadAcross=True )", expectList )
	
	expectList = [['a','b','c'],['d','e','f'],['g']]
	TEST( "PlaceInColumns( itemList, 3, flReadAcross=True, flReturnAsRows=True )", expectList )


More information about the Twisted-web mailing list