【问题标题】:How to avoid strange whitespaces in django template?如何避免 django 模板中出现奇怪的空格?
【发布时间】:2015-06-22 21:20:09
【问题描述】:

我正在使用 django 模板来呈现我的网页。在展开递归树的过程中发生了一些奇怪的事情(并且无空格标记没有帮助)。

这是我的递归模板:

index.html:

<ul class="Container">
    <li class="IsRoot">
        <div class="Expand">

        </div>

        <div class="Content">
            Содержание
        </div>



    </li>

    {% include 'list.html' with data=list %}

</ul>

和list.html(作为递归部分):

<ul class="Container">
    <li class="Node ExpandClosed">
        <div class="Expand"></div>
        <div class="Content">
            <a href="/help/{{data.name}}">
                {{data.content}}
            </a>
        </div>
        {% for item in data.decendent %}
            {% include 'list.html' with data=item %}
        {% endfor %}
    </li>
</ul>

结果如下:

使用 open("index.html", 'r').read() 作为 html-file 内容读取的文件的 html 内容被提取为文本,而不是 html:

<div id="frame" style="float:left; margin-left:310px;">
        &lt;!DOCTYPE html&gt;
        &lt;html&gt;
            &lt;head&gt;
                &lt;title&gt;hello&lt;/title&gt;
            &lt;/head&gt;
            &lt;body&gt;
                Body Great Style
            &lt;/body&gt;
        &lt;/html&gt;
</div>

而且我在元素之间还有奇怪的空格:

如何避免这种奇怪的行为?谢谢!

【问题讨论】:

    标签: python html django django-templates


    【解决方案1】:

    {% spaceless %} 仅删除标签之间的空格,而不是文本中的空格。文档中有描述:https://docs.djangoproject.com/en/2.0/ref/templates/builtins/#spaceless

    如果您还想删除文本中的空格,您可以使用自定义模板标签,如https://gist.github.com/martinsvoboda/1bf965a8c6037c0fe1a88d89ea822df6。用法:

    {% nospaces %}
    <strong>
        Hello
        this is text
    </strong>
    {% nospaces %}
    

    渲染

    <strong>Hello this is text</strong>
    

    【讨论】:

      【解决方案2】:

      {% spaceless %} YOUR CONTENT {% endspaceless %}

      【讨论】:

      【解决方案3】:

      您可以使用autoescape off(小心!):

      {% autoescape off %}
          {{data.content}}
      {% endautoescape %}
      

      请参阅this link 了解更多信息。您还想看看safe

      【讨论】:

      • 不幸的是,它不适用于我的情况。我完全按照你说的做了:take.ms/hiy1u,但是没有效果:take.ms/GLUuG
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-16
      • 1970-01-01
      • 1970-01-01
      • 2022-12-05
      • 2016-12-09
      • 2017-08-05
      • 2011-08-06
      相关资源
      最近更新 更多