Commits

anti_social committed 0641b9a

Improved html_params utility function.

Comments (0)

Files changed (1)

wtforms/widgets.py

     'TextInput',
 )
 
+def escape(s, quote=None):
+    if hasattr(s, '__html__'):
+        return s
+    return cgi.escape(unicode(s), quote=quote)
 
 def html_params(**kwargs):
     """
     frequent use of the normally reserved keywords `class` and `for`, suffixing
     these with an underscore will allow them to be used.
 
-    >>> html_params(name='text1', id='f', class_='text')
-    u'class="text" id="f" name="text1"'
+    >>> html_params(name='text1', id='f', class_=['text', 'short'], value=None)
+    u' class="text short" id="f" name="text1"'
     """
-    params = []
-    for k,v in sorted(kwargs.iteritems()):
-        if k in ('class_', 'class__', 'for_'):
+    params = {}
+    attrs = []
+    for k, v in sorted(kwargs.iteritems()):
+        if v is None:
+            continue
+        if k.endswith('_'):
             k = k[:-1]
-        params.append(u'%s="%s"' % (unicode(k), escape(unicode(v), quote=True)))
-    return u' '.join(params)
+        if isinstance(v, (list, tuple)):
+            params.setdefault(k, []).extend(v)
+        else:
+            params.setdefault(k, []).append(v)
+    for k, v in sorted(params.iteritems()):
+        attrs.append(u'%s="%s"' % (unicode(k), u' '.join([escape(w, quote=True) for w in v])))
+    if attrs:
+        return u' %s' % u' '.join(attrs)
+    return u''
 
 class HTMLString(unicode):
     def __html__(self):
         return self
-
-def escape(s, quote=None):
-    # print s, type(s)
-    if hasattr(s, '__html__'):
-        return s
-    return cgi.escape(unicode(s), quote=quote)
-
+    
+    def __add__(self, rhs):
+        t = super(HTMLString, self).__add__(rhs)
+        if hasattr(rhs, '__html__'):
+            return HTMLString(t)
+        return t
 
 class ListWidget(object):
     """
     """
     def __call__(self, field, **kwargs): 
         kwargs.setdefault('id', field.id)
-        return HTMLString(u'<textarea %s>%s</textarea>' % (html_params(name=field.name, **kwargs), escape(unicode(field._value()))))
+        return HTMLString(u'<textarea %s>%s</textarea>' % (html_params(name=field.name, **kwargs), escape(field._value())))
 
 class Select(object):
     """