Comma separated lists in django templates

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

    Django doesn't have support for this out-of-the-box. You can define a custom filter for this:

    from django import template
    
    
    register = template.Library()
    
    
    @register.filter
    def join_and(value):
        """Given a list of strings, format them with commas and spaces, but
        with 'and' at the end.
    
        >>> join_and(['apples', 'oranges', 'pears'])
        "apples, oranges, and pears"
    
        """
        # convert numbers to strings
        value = [str(item) for item in value]
    
        if len(value) == 1:
            return value[0]
    
        # join all but the last element
        all_but_last = ", ".join(value[:-1])
        return "%s, and %s" % (all_but_last, value[-1])
    

    However, if you want to deal with something more complex than just lists of strings, you'll have to use an explicit {% for x in y %} loop in your template.

提交回复
热议问题