Alasdair Alasdair - 1 year ago 196
Python Question

Comma separated lists in django templates


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.

Answer Source

I would suggest a custom django templating filter rather than a custom tag -- filter is handier and simpler (where appropriate, like here). {{ fruits | joinby:", " }} looks like what I'd want to have for the purpose... with a custom joinby filter:

def joinby(value, arg):
    return arg.join(value)

which as you see is simplicity itself!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download