Add list_or_value template filter.
[matthijs/projects/xerxes.git] / tools / templatetags / list.py
1 from django import template
2 from django.template.defaultfilters import unordered_list
3 from django.utils.safestring import mark_safe
4
5 """
6     Template tags and filters for working with lists.
7 """
8
9 register = template.Library()
10
11 @register.filter(name='list_or_value')
12 def list_or_value(list, autoescape=None):
13     """
14     Turn a list into a simple string or unordered list.
15
16     If the list is empty, returns an empty string.
17     If the list contains one element, returns just that element.
18     If the list contains more elements, return an ordered list with
19     those elements (Just like the builtin unordered_list, but with the
20     <ul> tags).
21     """
22     if len(list) == 0:
23         return ''
24     elif len(list) == 1:
25         return list[0]
26     else:
27         return mark_safe('<ul>' + unordered_list(list, autoescape=autoescape) + '</ul>')
28 list_or_value.needs_autoescape = True