Here is one that I wrote using the "max items" function:
useserialcomma = True def listify(values, maxitems=4): sercomma = ',' if useserialcomma else '' l = len(values) if l == 0: return '' elif l == 1: return values[0] elif l == 2: return values[0] + ' and ' + values[1] elif l <= maxitems: return ', '.join(values[:l-1]) + sercomma + ' and ' + values[-1] else: andmoretxt = ' and %d more' % (l - maxitems) return ', '.join(values[:maxitems]) + andmoretxt
This filter allows you to specify the maximum number of elements that you want to display. So, given this list:
myitems = ['foo', 'bar', 'baz', 'barn', 'feast', 'pizza']
this code in your template:
{{ myitems|listify:3 }}
gives:
foo, bar, baz and 3 others
source share