Commits

Mike Orr committed e31480e

webhelpers.tags.css_classes() adds classes to a tag programmatically.

  • Participants
  • Parent commits a19f8a9

Comments (0)

Files changed (2)

 * webhelpers.feedgenerator:
   - ``rfc3339_date`` now accepts date objects without crashing.
 * webhelprs.html.tags:
+  - New helper ``css_classes()`` to add classes to a tag programmatically.
   - Fix bug in tag helpers when passing 'id_' argument (although 'id' is
     recommended instead).
 * webhelpers.paginate:

webhelpers/html/tags.py

            # Head tags
            "stylesheet_link", "javascript_link", "auto_discovery_link",
            # Utility functions
-           "convert_boolean_attrs",
+           "css_classes", "convert_boolean_attrs",
            ]
 
 NL = literal("\n")
         attrs['height'] = height
     return HTML.img(src=url, alt=alt, **attrs)
 
+#### Non-tag utilities
+
+def css_classes(value_condition_pairs):
+    """Add CSS classes to a tag programmatically.
+
+    This helper is meant to be used as the ``class_`` argument to a tag helper.
+
+    The argument is an iterable of ``(class, condition)`` pairs, where each
+    ``class`` is a string and ``condition`` is a boolean.  The function 
+    returns a space-separated list of classes whose conditions were true.
+
+    If all conditions are false, return ``None``.  This tells the caller to
+    suppress the "class" attribute entirely.
+
+    Examples::
+
+        >>> arg = [("first", False), ("even", True)]
+        >>> HTML.td("My content.", class_=css_classes(arg))
+        literal(u'<td class="even">My content.</td>')
+        >>> arg = [("first", True), ("even", True)]
+        >>> HTML.td("My content.", class_=css_classes(arg))
+        literal(u'<td class="first even">My content.</td>')
+        >>> arg = [("first", False), ("even", False)]
+        >>> HTML.td("My content.", class_=css_classes(arg))
+        literal(u'<td>My content.</td>')
+
+ 
+    """
+    classes = []
+    for value, condition in value_condition_pairs:
+        if condition:    # Or ``if condition and value``
+            classes.append(value)
+    if not classes:
+        return None
+    return " ".join(classes)
+
+
 #### Tags for the HTML head
 
 def javascript_link(*urls, **attrs):