Ala*_*air 68 python django list django-templates
如果fruits是列表['apples', 'oranges', 'pears'],
有没有一种使用django模板标签生成"苹果,橘子和梨"的快捷方式?
我知道使用循环和{% if counter.last %}语句来做这个并不困难,但因为我将反复使用这个,我想我将不得不学习如何编写自定义标签 过滤器,如果它已经完成,我不想重新发明轮子.
作为延伸,我试图放弃牛津逗号(即返回"苹果,橘子和梨")甚至更加混乱.
S.L*_*ott 131
第一选择:使用现有的连接模板标记.
http://docs.djangoproject.com/en/dev/ref/templates/builtins/#join
这是他们的榜样
{{ value|join:" // " }}
Run Code Online (Sandbox Code Playgroud)
第二选择:在视图中执行.
fruits_text = ", ".join( fruits )
Run Code Online (Sandbox Code Playgroud)
提供fruits_text给模板进行渲染.
Mic*_*mim 66
这是一个超级简单的解决方案.将此代码放入comma.html:
{% if not forloop.last %}{% ifequal forloop.revcounter 2 %} and {% else %}, {% endifequal %}{% else %}{% endif %}
Run Code Online (Sandbox Code Playgroud)
现在无论你把逗号放在哪里,都要包含"comma.html":
{% for cat in cats %}
Kitty {{cat.name}}{% include "comma.html" %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
Ale*_*lli 34
我建议使用自定义django模板过滤器而不是自定义标签 - 过滤器更方便,更简单(在适当的地方,就像这里一样).{{ fruits | joinby:", " }}看起来像我想要的目的......使用自定义joinby过滤器:
def joinby(value, arg):
return arg.join(value)
Run Code Online (Sandbox Code Playgroud)
正如你所看到的那样简单!
小智 27
在Django模板上,您需要做的就是在每个水果之后建立一个逗号.一旦达到最后的果实,逗号就会停止.
{% if not forloop.last %}, {% endif %}
Run Code Online (Sandbox Code Playgroud)
这是我为解决我的问题所写的过滤器(它不包括牛津逗号)
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])
Run Code Online (Sandbox Code Playgroud)
要在模板中使用它: {{ fruits|join_with_commas }}