Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django template filter to create an list of items that join on commas and end on "and"

I feel like I am writing something that should already exist.

Does Django have a template filter that joins a list of items on commas and places and 'and' before the last one?

For example:

a = ['foo',]
b = ['bar', 'baz',]
c = a + b
d = c + ['yourmom',]

The filter I am looking for would display each list in the following ways:

a would display 'foo'.
b would display'bar and baz'.
c would display 'foo, bar, and baz'.
d would display 'foo, bar, baz, and yourmom'.

QUESTION 1: Is there something that does that already?


I tried to write this myself and it is breaking in two places:

My code: http://pastie.org/private/fhtvg5tchtwlnrdyuoyeja

QUESTION 2: It breaks on forloop.counter & tc.author.all|length. Please explain why these are not valid.

like image 582
jackiekazil Avatar asked Dec 13 '22 20:12

jackiekazil


1 Answers

You can do it in your template:

{% for item in list %}
    {% if forloop.first %}{% else %}
        {% if forloop.last %} and {% else %}, {% endif %}
    {% endif %}{{item}}
{% endfor %}


line breaks added for clarity: remove them in order to avoid unwanted blank spaces in your output:

{% for item in list %}{% if forloop.first %}{% else %}{% if forloop.last %} and {% else %}, {% endif %}{% endif %}{{item}}{% endfor %}


Edit: Changed code. Thanks to Eric Fortin for making me notice that I was confused.

like image 152
dolma33 Avatar answered May 26 '23 11:05

dolma33