Comma separated lists in django templates

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

    If you like one-liners:

    @register.filter
    def lineup(ls): return ', '.join(ls[:-1])+' and '+ls[-1] if len(ls)>1 else ls[0]
    

    and then in the template:

    {{ fruits|lineup }}
    

提交回复
热议问题