Skip to content

Instantly share code, notes, and snippets.

@RhubarbSin
Created July 9, 2014 15:31
Show Gist options
  • Save RhubarbSin/33a8b7d42328fe1b0c32 to your computer and use it in GitHub Desktop.
Save RhubarbSin/33a8b7d42328fe1b0c32 to your computer and use it in GitHub Desktop.
Subclass of web.py's GroupedDropdown that allows mixing option groups with plain options
import web
class MyGroupedDropdown (web.form.GroupedDropdown):
"""Subclass of GroupedDropdown that allows mixing option groups
with plain options, i.e. accepts tuples of strings as well as
tuples of tuples of strings.
>>> MyGroupedDropdown(name='example', args=(('Swedish Cars',
(('v', 'Volvo'), ('s', 'Saab'))), ('German Cars', (('m', 'Mercedes'),
('a', 'Audi'))), ('d', 'Delorean')), value='a').render()
u'<select id="example" name="example">\n <optgroup label="Swedish
Cars">\n <option value="v">Volvo</option>\n <option
value="s">Saab</option>\n </optgroup>\n <optgroup label="German
Cars">\n <option value="m">Mercedes</option>\n <option
selected="selected" value="a">Audi</option>\n </optgroup>\n
<option value="d">Delorean</option>\n</select>\n'
"""
def render(self):
attrs = self.attrs.copy()
attrs['name'] = self.name
x = '<select %s>\n' % attrs
for arg in self.args:
if (isinstance(arg, (list, tuple)) and
isinstance(arg[1], (list, tuple))):
label, options = arg
x += ' <optgroup label="%s">\n' % web.net.websafe(label)
for opt in options:
x += self._render_option(opt, indent = ' ')
x += ' </optgroup>\n'
else:
x += self._render_option(arg, indent = ' ')
x += '</select>\n'
return x
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment