Django templates whitespaces ans empty characters in for loop

邮差的信 提交于 2019-12-11 09:48:40

问题


I have a piece of django template responsible for listing some labels if there are in passed list 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>

What results in:

<div id="selected-sources" style="min-height:150px; max-height:500px">

</div>

when sources is empty.

But I would like it to render like this:

<div id="selected-sources" style="min-height:150px; max-height:500px"></div>

Is it only solution to code it like this:

<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>

UPDATE: by small modification, but making code looking bit dirty I get rid of this extra line breaks:

<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>

回答1:


you can easily get rid of all the unnecessary spaces django produces by using: {% spaceless %} tag see 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 %}



回答2:


If I am understanding this correctly, you could do something like it says 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 %}


来源:https://stackoverflow.com/questions/25086003/django-templates-whitespaces-ans-empty-characters-in-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!