Comma separated lists in django templates

后端 未结 11 1210
梦如初夏
梦如初夏 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:29

    Here's the filter I wrote to solve my problem (it doesn't include the Oxford comma)

    def join_with_commas(obj_list):
        """Takes a list of objects and returns their string representations,
        separated by commas and with 'and' between the penultimate and final items
        For example, for a list of fruit objects:
        [, , ] -> 'apples, oranges and pears'
        """
        if not obj_list:
            return ""
        l=len(obj_list)
        if l==1:
            return u"%s" % obj_list[0]
        else:    
            return ", ".join(str(obj) for obj in obj_list[:l-1]) \
                    + " and " + str(obj_list[l-1])
    

    To use it in the template: {{ fruits|join_with_commas }}

提交回复
热议问题