[Zope] Dynamic sorting with dtml-in

Duncan Booth duncan@rcp.co.uk
Tue, 1 Feb 2000 09:48:34 +0000


> Any Ideas? Or do I have to rewrite the complete show_table to
> "show_table_sort_title"-stuff and call each seperately? There nust be a
> more Zopish thing to get that working.
> 
One way is to produce a separate method for each sort key and 
factor out the body of the loop into a separate method:
So show_table_sort_title becomes:
<dtml-in "objectValues('type') sort=title>  
  <dtml-var show_table_body>
</dtml-in>

One nice feature with this is that you can have a show_table_body 
method for the default display, but override it as necessary.

If your data was in a database, the best way is to sort the database 
query. However, since it isn't, you may end up having to do 
something like the code below (this is a complete runnable example):

<dtml-unless sortkey><dtml-call "REQUEST.set('sortkey', 
'bobobase_modification_time')"></dtml-unless>
<table>
<dtml-let list="[]">
<dtml-in "objectValues(['DTML Document', 'DTML Method'])">
  <dtml-let item="_.getitem('sequence-item', 0)" key="_[sortkey]">
    <dtml-call "list.append((key,item))">
  </dtml-let>
</dtml-in>
<dtml-call "list.sort()">
<dtml-if reverse><dtml-call "list.reverse()"></dtml-if>
<dtml-in list>
  <tr><td><dtml-var title></td>
<td><dtml-var bobobase_modification_time 
fmt="%Y/%m/%d"></td></tr>
</dtml-in>
</dtml-let>
</table>

The steps performed above are:

1. Set up default sort key.
2. Copy the list into a fresh list containing tuples with the desired key 
as element 0 and the original item as element 1. You can make this 
step more complicated, for example lowercasing the key if you want 
a case insensitive sort.
3. Sort the new list and optionally reverse it. If you never want to 
reverse the sort, leave out these two lines and change <dtml-in list> 
to <dtml-in list sort>
4. Insert your table body here.

-- 
Duncan Booth                                             duncan@dales.rmplc.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?
http://dales.rmplc.co.uk/Duncan