Add list_or_value template filter.
[matthijs/projects/xerxes.git] / tools / templatetags / list.py
diff --git a/tools/templatetags/list.py b/tools/templatetags/list.py
new file mode 100644 (file)
index 0000000..e0111b0
--- /dev/null
@@ -0,0 +1,28 @@
+from django import template
+from django.template.defaultfilters import unordered_list
+from django.utils.safestring import mark_safe
+
+"""
+    Template tags and filters for working with lists.
+"""
+
+register = template.Library()
+
+@register.filter(name='list_or_value')
+def list_or_value(list, autoescape=None):
+    """
+    Turn a list into a simple string or unordered list.
+
+    If the list is empty, returns an empty string.
+    If the list contains one element, returns just that element.
+    If the list contains more elements, return an ordered list with
+    those elements (Just like the builtin unordered_list, but with the
+    <ul> tags).
+    """
+    if len(list) == 0:
+        return ''
+    elif len(list) == 1:
+        return list[0]
+    else:
+        return mark_safe('<ul>' + unordered_list(list, autoescape=autoescape) + '</ul>')
+list_or_value.needs_autoescape = True