Use force_unicode() instead of .__unicode__().
[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 from django.utils.encoding import force_unicode
5 from django.utils.translation import ugettext as _
6
7 """
8     Template tags and filters for working with lists.
9 """
10
11 register = template.Library()
12
13 @register.filter(name='list_or_value')
14 def list_or_value(list, autoescape=None):
15     """
16     Turn a list into a simple string or unordered list.
17
18     If the list is empty, returns an empty string.
19     If the list contains one element, returns just that element.
20     If the list contains more elements, return an ordered list with
21     those elements (Just like the builtin unordered_list, but with the
22     <ul> tags).
23     """
24     if len(list) == 0:
25         return ''
26     elif len(list) == 1:
27         return list[0]
28     else:
29         return mark_safe('<ul>' + unordered_list(list, autoescape=autoescape) + '</ul>')
30 list_or_value.needs_autoescape = True
31
32 @register.filter(name='natural_list')
33 def natural_list(list):
34     """
35     Turns the list into a natural list, using comma's and "and" for
36     joining the terms. The result is somewhat localized (but probably
37     insufficient for language that use completely different
38     interpunction for lists).
39     """
40     if len(list) == 0:
41         return ''
42     res = ''
43     for item in list[0:-1]:
44         if res:
45             res += ', '
46         res += force_unicode(item)
47
48     if res:
49         res += ' %s ' % _('and')
50
51     res += force_unicode(list[-1])
52
53     return res 
54 natural_list.is_safe = True