Comma separated lists in django templates

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

    I think the simplest solution might be:

    @register.filter
    def comma_list(p_values: Iterable[str]) -> List[str]:
        values = list(p_values)
        if len(values) > 1:
            values[-1] = u'and %s' % values[-1]
        if len(values) > 2:
            return u', '.join(values)
        return u' '.join(values)
    
    

提交回复
热议问题