如果fruits
是列表['apples', 'oranges', 'pears']
,
有没有一种使用Django模板标签快速生成"苹果、橙子和梨"的方法?
我知道使用一个循环和{% if counter.last %}
条语句来实现这一点并不困难,但因为我要反复使用它,我想我必须学习如何编写自定义的标记过滤器,如果已经完成了,我不想重新发明轮子.
作为扩展,我试图放弃Oxford Comma(即返回"苹果、橙子和梨")的try 更为混乱.
如果fruits
是列表['apples', 'oranges', 'pears']
,
有没有一种使用Django模板标签快速生成"苹果、橙子和梨"的方法?
我知道使用一个循环和{% if counter.last %}
条语句来实现这一点并不困难,但因为我要反复使用它,我想我必须学习如何编写自定义的标记过滤器,如果已经完成了,我不想重新发明轮子.
作为扩展,我试图放弃Oxford Comma(即返回"苹果、橙子和梨")的try 更为混乱.
这是我为解决问题而写的过滤(不含牛津逗号)
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:
[<Fruit: apples>, <Fruit: oranges>, <Fruit: pears>] -> '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])
在模板中使用:{{ fruits|join_with_commas }}