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