David542
David542

Reputation: 110512

Convert list to comma separate values in django template

In a view I can do:

l = ['one', 'two', 'three']
', '.join(l)
>>> 'one, two, three'

Is there a way to do the same in the template, or do I need to create a custom template filter?

Upvotes: 5

Views: 7125

Answers (2)

C.B.
C.B.

Reputation: 8346

There is a builtin filter for this. From the docs

Filter arguments that contain spaces must be quoted; for example, to join a list with commas and spaces you’d use {{ list|join:", " }}.

Upvotes: 19

David542
David542

Reputation: 110512

This would be the template filter:

@register.filter
def list_to_comma_separated_string(l):
    try:
        return ', '.join(l)
    except:
        return None

Upvotes: 0

Related Questions