django 模板中的逗号分隔列表 [英] Comma separated lists in django templates

查看:39
本文介绍了django 模板中的逗号分隔列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果 fruits 是列表 ['apples', 'oranges', 'pears'],

是否有使用 django 模板标签生成apples, oranges, and pears"的快速方法?

is there a quick way using django template tags to produce "apples, oranges, and pears"?

我知道使用循环和 {% if counter.last %} 语句来做到这一点并不难,但是因为我要反复使用它,所以我想我会学习如何编写自定义 tags 过滤器,如果已经完成,我不想重新发明轮子.

I know it's not difficult to do this using a loop and {% if counter.last %} statements, but because I'm going to use this repeatedly I think I'm going to have to learn how to write custom tags filters, and I don't want to reinvent the wheel if it's already been done.

作为扩展,我尝试删除 牛津逗号(即返回apples, oranges和梨")甚至更乱.

As an extension, my attempts to drop the Oxford Comma (ie return "apples, oranges and pears") are even messier.

推荐答案

这是我为解决问题而编写的过滤器(不包括牛津逗号)

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:
    [<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 }}

这篇关于django 模板中的逗号分隔列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆