Django模板中的逗号分隔列表
如果 fruits
是这个列表 ['apples', 'oranges', 'pears']
,
有没有什么简单的方法可以用 Django 模板标签来生成“apples, oranges, and pears”这样的字符串呢?
我知道用循环和 {% if counter.last %}
语句来实现这个并不难,但因为我会多次使用这个功能,所以我觉得我得学会怎么写自定义的 标签 过滤器。如果已经有人做过这个,我就不想重复造轮子了。
另外,我尝试去掉 牛津逗号(也就是返回“apples, oranges and pears”)的做法也更麻烦。
12 个回答
77
这里有一个非常简单的解决方案。把下面的代码放到一个叫做comma.html的文件里:
{% if not forloop.last %}{% ifequal forloop.revcounter 2 %} and {% else %}, {% endifequal %}{% else %}{% endif %}
然后在你想放逗号的地方,直接用"comma.html"来替代:
{% for cat in cats %}
Kitty {{cat.name}}{% include "comma.html" %}
{% endfor %}
更新:@user3748764给我们提供了一个稍微简洁一点的版本,没有使用过时的ifequal语法:
{% if not forloop.first %}{% if forloop.last %} and {% else %}, {% endif %}{% endif %}
注意,这个代码应该放在元素之前,而不是之后。
158
第一种选择:使用现有的连接模板标签。
http://docs.djangoproject.com/en/dev/ref/templates/builtins/#join
这是他们的例子:
{{ value|join:" // " }}
第二种选择:在视图中处理。
fruits_text = ", ".join( fruits )
把 fruits_text
提供给模板进行渲染。
9
这是我写的一个过滤器,用来解决我的问题(它不包括牛津逗号)
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 }}