Comma separated lists in django templates


If fruits is the list ['apples', 'oranges', 'pears'],

is there a quick way using django template tags to produce "apples, oranges, and pears"?

I know it's not difficult to do this using a loop and {% if counter.last %} statements, but because I'm going to use this repeatedly I think I'm going to have to learn how to write custom tags filters, and I don't want to reinvent the wheel if it's already been done.

As an extension, my attempts to drop the Oxford Comma (ie return "apples, oranges and pears") are even messier.

8/6/2009 2:58:34 AM

Accepted Answer

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:
    [<Fruit: apples>, <Fruit: oranges>, <Fruit: pears>] -> 'apples, oranges and pears'
    if not obj_list:
        return ""
    if l==1:
        return u"%s" % obj_list[0]
        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 }}

10/11/2018 9:12:29 AM

First choice: use the existing join template tag.

Here's their example

{{ value|join:" // " }}

Second choice: do it in the view.

fruits_text = ", ".join( fruits )

Provide fruits_text to the template for rendering.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow