Anonymous committed 95bff36

Factor out formatting HTML attributes.

Comments (0)

Files changed (1)


         args = kw.pop("c")
     closed = kw.pop("_closed", True)
     nl = kw.pop("_nl", False)
-    htmlArgs = [' %s="%s"' % (_attr_decode(attr), escape(value))
-                for attr, value in sorted(kw.iteritems())
-                if value is not None]
+    attrs_str = format_attrs(**kw)
     if not args and tag in empty_tags and closed:
         substr = '<%s%s />'
-        html = literal(substr % (tag, "".join(htmlArgs)))
+        html = literal(substr % (tag, attrs_str))
-        chunks = ["<%s%s>" % (tag, "".join(htmlArgs))]
+        chunks = ["<%s%s>" % (tag, attrs_str)]
         chunks.extend(escape(x) for x in args)
         if closed:
             chunks.append("</%s>" % tag)
         html += "\n"
     return literal(html)
+def format_attrs(**attrs):
+    """Format HTML attributes into a string of ' key="value"' pairs which
+    can be inserted into an HTML tag.
+    The attributes are sorted alphabetically.  If any value is None, the entire
+    attribute is suppressed.
+    Usage:
+    >>> format_attrs(p=2, q=3)
+    literal(u' p="2" q="3"')
+    >>> format_attrs(p=2, q=None)
+    literal(u' p="2"')
+    >>> format_attrs(p=None)
+    literal(u'')
+    """
+    strings = [u' %s="%s"' % (_attr_decode(attr), escape(value))
+        for attr, value in sorted(attrs.iteritems())
+        if value is not None]
+    return literal("".join(strings))
 class literal(unicode):
     """Represents an HTML literal.
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.