If fruits
is the list [\'apples\', \'oranges\', \'pears\']
,
is there a quick way using django template tags to produce \"apples, oranges, and p
Here's the filter I wrote to solve my problem (it doesn't include the Oxford comma)
def join_with_commas(obj_list):
"""Takes a list of objects and returns their string representations,
separated by commas and with 'and' between the penultimate and final items
For example, for a list of fruit objects:
[, , ] -> 'apples, oranges and pears'
"""
if not obj_list:
return ""
l=len(obj_list)
if l==1:
return u"%s" % obj_list[0]
else:
return ", ".join(str(obj) for obj in obj_list[:l-1]) \
+ " and " + str(obj_list[l-1])
To use it in the template: {{ fruits|join_with_commas }}