| 147 | class SelectGrouped(Select): |
| 148 | def render(self, name, value, attrs=None, choices=()): |
| 149 | if value is None: value = '' |
| 150 | final_attrs = self.build_attrs(attrs, name=name) |
| 151 | output = [u'<select%s>' % flatatt(final_attrs)] |
| 152 | str_value = smart_unicode(value) # Normalize to string. |
| 153 | for group_label, group_choices in chain(self.choices, choices): |
| 154 | output.append(u'<optgroup label="%s">' % escape(smart_unicode(group_label))) |
| 155 | for option_value, option_label in group_choices: |
| 156 | option_value = smart_unicode(option_value) |
| 157 | option_label = smart_unicode(option_label) |
| 158 | selected_html = (option_value == str_value) and u' selected="selected"' or '' |
| 159 | output.append(u'<option value="%s"%s>%s</option>' % (escape(option_value), selected_html, escape(option_label))) |
| 160 | output.append(u'</optgroup>') |
| 161 | output.append(u'</select>') |
| 162 | return u'\n'.join(output) |
| 163 | |
| 187 | class SelectMultipleGrouped(SelectMultiple): |
| 188 | def render(self, name, value, attrs=None, choices=()): |
| 189 | if value is None: value = [] |
| 190 | final_attrs = self.build_attrs(attrs, name=name) |
| 191 | output = [u'<select multiple="multiple"%s>' % flatatt(final_attrs)] |
| 192 | str_values = set([smart_unicode(v) for v in value]) # Normalize to strings. |
| 193 | for group_label, group_choices in chain(self.choices, choices): |
| 194 | output.append(u'<optgroup label="%s">' % escape(smart_unicode(group_label))) |
| 195 | for option_value, option_label in group_choices: |
| 196 | option_value = smart_unicode(option_value) |
| 197 | option_label = smart_unicode(option_label) |
| 198 | selected_html = (option_value in str_values) and u' selected="selected"' or '' |
| 199 | output.append(u'<option value="%s"%s>%s</option>' % (escape(option_value), selected_html, escape(option_label))) |
| 200 | output.append(u'</optgroup>') |
| 201 | output.append(u'</select>') |
| 202 | return u'\n'.join(output) |
| 203 | |