On my blog, I have a many-to-many relation between entries and
categories, and in the sidebar of an entry I display the list of
categories. For example:
The entry at http://www.b-list.org/weblog/2007/dec/04/magic-tags/
belongs to one category, and so displays
"It's part of the category Django."
The entry at http://www.b-list.org/weblog/2007/feb/16/javascript-knowledge-gap/
is part of two categories, and so displays
"It's part of the categories JavaScript and Programming."
The entry at http://www.b-list.org/weblog/2007/jan/22/choosing-javascript-library/
is in three categories, and so displays
"It's part of the categories Frameworks, JavaScript and Programming."
The template snippet which does this is actually pretty simple:
It’s part of the categor{{
object.categories.count|pluralize:"y,ies" }} {% for category in
object.categories.all %}<a href="{{ category.get_absolute_url }}">{{
category.title }}</a>{% if forloop.last %}{% else %}{% ifequal
forloop.revcounter0 1 %} and {% else %}, {% endifequal %} {% endif
%}{% endfor %}.
In short:
1. Pluralize "category" appropriately to "categories" when there's
more than one category for the entry.
2. Loop through the categories.
3. Each time through, link to the category and show its title.
4. On the last trip through the loop, don't do anything special.
5. Otherwise, if it's the next-to-last time display a space followed
by the word "and" followed by a space.
6. Otherwise, display a comma followed by a space.
I don't like the serial comma (e.g., I prefer "Frameworks, JavaScript
and Programming" to "Frameworks, JavaScript, and Programming"), but
that'd be easy enough to do by changing step 5 to show "and," instead
of "and".
--
"Bureaucrat Conrad, you are technically correct -- the best kind of correct."