If fruits
is the list [\'apples\', \'oranges\', \'pears\']
,
is there a quick way using django template tags to produce \"apples, oranges, and p
Here's a super simple solution. Put this code into comma.html:
{% if not forloop.last %}{% ifequal forloop.revcounter 2 %} and {% else %}, {% endifequal %}{% else %}{% endif %}
And now wherever you'd put the comma, include "comma.html" instead:
{% for cat in cats %}
Kitty {{cat.name}}{% include "comma.html" %}
{% endfor %}
Update: @user3748764 gives us a slightly more compact version, without the deprecated ifequal syntax:
{% if not forloop.first %}{% if forloop.last %} and {% else %}, {% endif %}{% endif %}
Note that it should be used before the element, not after.