【问题标题】:Django templates whitespaces ans empty characters in for loopDjango在for循环中模板空格和空字符
【发布时间】:2014-09-24 23:57:03
【问题描述】:

我有一个 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>

【问题讨论】:

标签: django django-templates


【解决方案1】:

您可以使用以下方法轻松摆脱 django 产生的所有不必要的空格:{% spaceless %} 标签参见文档: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】:

    如果我理解正确的话,你可以像 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 %}
    

    【讨论】:

    • 唷.. 好的。我迷茫了一秒。我还没有真正遇到过另一种做你需要的方式
    猜你喜欢
    • 2012-07-25
    • 2016-10-16
    • 1970-01-01
    • 1970-01-01
    • 2013-06-30
    • 2010-11-09
    • 2012-04-19
    • 2021-10-17
    相关资源
    最近更新 更多