Comma separated lists in django templates

后端 未结 11 1199
梦如初夏
梦如初夏 2021-01-30 16:00

If fruits is the list [\'apples\', \'oranges\', \'pears\'],

is there a quick way using django template tags to produce \"apples, oranges, and p

11条回答
  •  野的像风
    2021-01-30 16:24

    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.

提交回复
热议问题