2012-07-07 207 views
4

我有以下代码:在Django模板使用spaceless

{% for item in profile.jobs.all %} 
     {% if not forloop.first %}, {% endif %}{{ item }} 
    {% endfor %} 

将会产生类似如下:

"Programmer , Plumber , Philosopher" 

我不想逗号前面有一个空间,但唯一的办法我已经能够摆脱它是将它压缩到一条线上,这降低了可读性:

{% for item in profile.jobs.all %}{% if not forloop.first %}, {% endif %}{{ item }}{% endfor %} 

Is there处理这个问题的更好方法是什么?

+2

我认为空间是由于{%if not forloop.first%}'之前的空格/缩进引起的。 – machaku 2012-07-07 11:03:19

回答

3

{%spaceless%}仅删除HTML标签之间的空格。

您可以使用{{值|加入: “”}}

或我相信这将工作:

{% for item in profile.jobs.all %} 
    {% if not forloop.first %}, {% endif %} 
    {{ item }} 
{% endfor %} 
0

,如果你用的什么东西像

{% if profile.jobs.count != 1 %} 
    {% for item in profile.jobs.all %} 
     {{ item }}{% if not forloop.last %}, {% endif %} 
    {% endfor %} 
{% else %} 
    {{item}} 
{% endif %}