Add natural_list template filter.
authorMatthijs Kooijman <matthijs@stdin.nl>
Fri, 16 Jan 2009 21:18:52 +0000 (22:18 +0100)
committerMatthijs Kooijman <matthijs@stdin.nl>
Fri, 16 Jan 2009 21:22:31 +0000 (22:22 +0100)
This template filter transforms lists like ['foo', 'bar', 'baz'] into a
natural list like 'foo, bar and baz'.

tools/templatetags/list.py

index e0111b00e4b03254915299a1844525a7cbead7d6..70ce860d978a0d03c83775ac5c4192e486f3cfa3 100644 (file)
@@ -1,6 +1,8 @@
 from django import template
 from django.template.defaultfilters import unordered_list
 from django.utils.safestring import mark_safe
+from django.utils.encoding import force_unicode
+from django.utils.translation import ugettext as _
 
 """
     Template tags and filters for working with lists.
@@ -26,3 +28,27 @@ def list_or_value(list, autoescape=None):
     else:
         return mark_safe('<ul>' + unordered_list(list, autoescape=autoescape) + '</ul>')
 list_or_value.needs_autoescape = True
+
+@register.filter(name='natural_list')
+def natural_list(list):
+    """
+    Turns the list into a natural list, using comma's and "and" for
+    joining the terms. The result is somewhat localized (but probably
+    insufficient for language that use completely different
+    interpunction for lists).
+    """
+    if len(list) == 0:
+        return ''
+    res = ''
+    for item in list[0:-1]:
+        if res:
+            res += ', '
+        res += item.__unicode__()
+
+    if res:
+        res += ' %s ' % _('and')
+
+    res += list[-1].__unicode__()
+
+    return res 
+natural_list.is_safe = True