If fruits
is the list [\'apples\', \'oranges\', \'pears\']
,
is there a quick way using django template tags to produce \"apples, oranges, and p
Django doesn't have support for this out-of-the-box. You can define a custom filter for this:
from django import template
register = template.Library()
@register.filter
def join_and(value):
"""Given a list of strings, format them with commas and spaces, but
with 'and' at the end.
>>> join_and(['apples', 'oranges', 'pears'])
"apples, oranges, and pears"
"""
# convert numbers to strings
value = [str(item) for item in value]
if len(value) == 1:
return value[0]
# join all but the last element
all_but_last = ", ".join(value[:-1])
return "%s, and %s" % (all_but_last, value[-1])
However, if you want to deal with something more complex than just lists of strings, you'll have to use an explicit {% for x in y %}
loop in your template.