{% for item in list %}
{% if not forloop.first %}
{% if not forloop.last %}
,
{% endif %}
{% endif %}
{% if forloop.last %}
and
{% endif %}
{{ item }}
{% endfor %}
{% for item in list %}{% if not forloop.first %}{% if not forloop.last %}, {% endif %}{% endif %}{% if forloop.last %} and {% endif %}{{ item }}{% endfor %}
顺便说一下,如果列表只包含一个值,那么模板将呈现错误的输出。更正的模板如下所示:
^{pr2}$
如果没有多余的空间,它就会变成:
{% for item in list %}{% if not forloop.first %}{% if forloop.last %} and {% else %}, {% endif %}{% endif %}{{ item }}{% endfor %}
@register.filter
def format_list(li):
"""
Return the list as a string in human readable format.
>>> format_list([''])
''
>>> format_list(['a'])
'a'
>>> format_list(['a', 'b'])
'a and b'
>>> format_list(['a', 'b', 'c'])
'a, b and c'
>>> format_list(['a', 'b', 'c', 'd'])
'a, b, c and d'
"""
if not li:
return ''
elif len(li) == 1:
return li[0]
return '%s and %s' % (', '.join(li[:-1]), li[-1])
>>> python -m doctest form.py -v
Trying:
format_list([''])
Expecting:
''
ok
Trying:
format_list(['a'])
Expecting:
'a'
ok
Trying:
format_list(['a', 'b'])
Expecting:
'a and b'
ok
Trying:
format_list(['a', 'b', 'c'])
Expecting:
'a, b and c'
ok
Trying:
format_list(['a', 'b', 'c', 'd'])
Expecting:
'a, b, c and d'
ok
1 items had no tests:
form
1 items passed all tests:
5 tests in form.format_list
5 tests in 2 items.
5 passed and 0 failed.
Test passed.
好吧,经过几次尝试,我想我找到了一个解决方案,它有点冗长,但它能满足您的需要-没有多余的空间-
forloop.revcounter
正在从循环的末尾开始倒数,因此您将“and”添加到最后一个项中,并将最后一个项保留为空。在Django插入模板包含的所有空格:
顺便说一下,如果列表只包含一个值,那么模板将呈现错误的输出。更正的模板如下所示:
^{pr2}$如果没有多余的空间,它就会变成:
我要做一个简单的template filter:
我还不是python方面的专家,可能还有更好的方法。但是,这在“django级别”上似乎很干净,就这样使用它:
^{pr2}$我喜欢这个解决方案的原因是它是可重用的,可读性更强,代码更少,并且有测试。在
有关如何安装的详细信息,请参阅writing template filters上的文档。在
另外,您可能会注意到这个函数带有doctest,请参考django documentation来了解如何运行测试。在
有个办法:
相关问题 更多 >
编程相关推荐