我有一块django模板负责列出一些标签,如果传递的列表sources
中有:
<div id="selected-sources" style="min-height:150px; max-height:500px">
{% for source in sources %}
<span id='{{source.0}}' class='tag_with_remove'>
<i class='icon-remove'></i>
<span class='label'>source: {{source.1}}</span>
</span>
{% endfor %}
</div>
结果如下:
<div id="selected-sources" style="min-height:150px; max-height:500px">
</div>
当sources
为空时。
但我希望它像这样呈现:
<div id="selected-sources" style="min-height:150px; max-height:500px"></div>
只是这样编码的解决方案:
<div id="selected-sources" style="min-height:150px; max-height:500px">{% for source in sources %}
<span id='{{source.0}}' class='tag_with_remove'><i class='icon-remove'></i><span class='label'>source: {{source.1}}</span></span>{% endfor %}</div>
更新: 通过小修改,但使代码看起来有点脏,我摆脱了这个额外的换行符:
<div id="selected-sources" style="min-height:150px; max-height:500px">{% for source in sources %}
<span id='{{source.0}}' class='tag_with_remove'>
<i class='icon-remove'></i>
<span class='label'>source: {{source.1}}</span>
</span>
{% endfor %}</div>
答案 0 :(得分:2)
你可以通过使用{% spaceless %}
标签轻松摆脱django产生的所有不必要的空格,参见doc:https://docs.djangoproject.com/en/dev/ref/templates/builtins/#spaceless
{% spaceless %}
<div id="selected-sources" style="min-height:150px; max-height:500px">
{% for source in sources %}
<span id='{{source.0}}' class='tag_with_remove'>
<i class='icon-remove'></i>
<span class='label'>source: {{source.1}}</span>
</span>
{% endfor %}
</div>
{% endspaceless %}
答案 1 :(得分:0)
如果我理解正确,你可以做一些像in the template docs:
这样的事情{% if sources %}
<div id="selected-sources" style="min-height:150px; max-height:500px">
{% for source in sources %}
<span id='{{source.0}}' class='tag_with_remove'>
<i class='icon-remove'></i>
<span class='label'>source: {{source.1}}</span>
</span>
{% endfor %}
</div>
{% else %}
<div id="selected-sources" style="min-height:150px; max-height:500px"></div>
{% endif %}