Humanize lists of strings in templates

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
@register.filter
def humanize_list(value):
    if len(value) == 0:
        return ""
    elif len(value) == 1:
        return value[0]

    s = ", ".join(value[:-1])

    if len(value) > 3:
        s += ","

    return "%s and %s" % (s, value[-1])

Comments

(Forgotten your password?)

You may use Markdown syntax here, but raw HTML will be removed.