[Twisted-web] Sorting an option list

Samuel Reynolds sam at SpinwardStars.com
Fri Jul 9 10:50:10 MDT 2004


At 2004-07-09 12:14 PM +0100, you wrote:
>This may not be solvable with nevow/stan but I'm hoping it may be...
>
>I'm doing
>
>return t.select(name="establishment")[
>         [
>             t.option(value=e['_oid'])[e['establishment_desc']]
>             for e in data
>         ]
>     ]
>
>to create a select list from data, where data is in the form
>
>[{'_oid': '1', 'establishment_desc': 'foo'},
>  {'_oid': '2', 'establishment_desc': 'bar'},
>  ... ]
>
>The drop down that is created really needs to be sorted alphabetically
>by the establishment_desc.
>
>I realise I can probably write a function to sort the data myself and
>pass it to data.sort(), but I was wondering if there was a way to do it
>with stan or nevow after the DOM has been created.
>
>--
>Ed.

Another "maybe not 'the nevow way,' but it works"....
I created this in about December out of frustration with
not begin able to get a select where value != label.
(May be possible now, I don't know.)
Also, this was before I (more or less) got the hang of stan.
But, as I said, it works.

In one application, all my pages derive from PageBase,
which defines render_myselect:

     def render_myselect(self, context, data):
         """
         Populate options in a select wgt.

         data is a list of dictionaries.
         Each dictionary has (at least) 'value' and 'label' fields.

         Usage: <select name='...' nevow:data='...' nevow:render='myselect' />
         """
         # Order by label for UI
         ordered = [(item['label'],item['value']) for item in data]
         ordered.sort()

         # Generate options
         tag = context.tag.clear()
         tag.children = []
         for item in ordered:
             tag.children.append( tags.option(value=item[1])[ item[0] ] )
         tag.renderer = None
         return tag

An example data_xx method:

     def data_testselect( self, context, data ):
         return [
                 {'value':1, 'label':'Alice'},
                 {'value':2, 'label':'Victor'},
                 {'value':3, 'label':'Clancy'},
                 {'value':4, 'label':'Nancy'},
             ]

... And in template (again, just an example):

<div>
     <b>Test Select</b>&nbsp;
     <select name='person' nevow:data='testselect' nevow:render='myselect' />
     <br />Selections should appear in the order
     Alice/Clancy/Nancy/Victor
</div>



__________________________________________________________
Spinward Stars, LLC                        Samuel Reynolds
Software Consulting and Development           303-805-1446
http://SpinwardStars.com/            sam at SpinwardStars.com 





More information about the Twisted-web mailing list