Pretty comma-separated lists

01
November
2008;
Django, Tutorials

Here is a quick tip for outputting lists. Often times you’ll have a short list of items that you want to output as a comma separated list. Things like a couple of contributing authors, the categories your entry is filed under, or the tags that a photo is tagged with. The first thought might be to try this:

(I am going to add line breaks and indentation to all of these for the sake of readability. However, in production you must remove all line breaks in these snippets or you will end up with spaces in places you don’t want them, like before a comma. (No, the {% spaceless %} tag won’t help.))

{% for tag in entry.tags.all %}
{{ tag.name }},
{% endfor %}

There is a problem with that method — even the last tag would have a comma after it. That feels tacky to me. We could improve it like so:

Beyond the {% if %} tag

That is syntax is what most people would use. The {% if %} tag is one of our most used tools, but there are other filters that can often be used instead and they may make our code more readable. The the same outcome could be achieved with:

Ah, the yesno filter. It is a beautiful thing. Two things two note about the following example:

yesno cannot output raw commas because they are used as the separator in the argument; but we can use an entity.

Our entities will be escaped unless we mark them with the safe filter.

Now one may argue that the yesno filter didn’t do much for us in this example, except make us look up the comma’s decimal entity. But the yesno filter can really shine. What if we wanted to typogrify our ampersand, wrapping it in a span element so we can style it? Using the if statement our snippet would look like so: