David542
David542

Reputation: 110093

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: 7123

Answers (2)

C.B.
C.B.

Reputation: 8326

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: 110093

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