django模板中的逗号分隔列表 [英] Comma separated lists in django templates
问题描述
如果 fruit
是列表 ['apples','oranges','pears']
,
有没有快速的方式使用django模板标签来生成苹果,橘子和梨?
我知道使用循环和 {%if counter.last%}
语句来执行此操作并不困难,但是由于我将重复使用这一点,我想我将要必须学习如何编写自定义标签过滤器,如果已经完成,我不想重新发明。
作为我试图放弃牛津逗号(即退回苹果,橘子和梨)是
我建议一个自定义django模板过滤器而不是自定义标签 - 过滤器更加简单(在适当的情况下,像这里)。 {{fruits |加入:,}}
看起来像我想要的目的...使用自定义 joinby
filter:
def joinby(value,arg):
return arg.join(value)
您所看到的只是简单本身!
If fruits
is the list ['apples', 'oranges', 'pears']
,
is there a quick way using django template tags to produce "apples, oranges, and pears"?
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.
As an extension, my attempts to drop the Oxford Comma (ie return "apples, oranges and pears") are even messier.
I would suggest a custom django templating filter rather than a custom tag -- filter is handier and simpler (where appropriate, like here). {{ fruits | joinby:", " }}
looks like what I'd want to have for the purpose... with a custom joinby
filter:
def joinby(value, arg):
return arg.join(value)
which as you see is simplicity itself!
这篇关于django模板中的逗号分隔列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!