Created
July 9, 2014 15:31
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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