如何避免 django 模板中出现奇怪的空格? [英] How to avoid strange whitespaces in django template?

查看:73
本文介绍了如何避免 django 模板中出现奇怪的空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 django 模板来呈现我的网页.在展开递归树的过程中发生了一些奇怪的事情(无空间标记无济于事).

这是我的递归模板:

index.html:

  • <div class="展开">

<div class="内容">Содержание

{% 包含 'list.html' 和 data=list %}

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

    <li class="Node ExpandClosed"><div class="展开"></div><div class="内容"><a href="/help/{{data.name}}">{{数据内容}}</a>

{% 用于 data.decendent 中的项目 %}{% 包含 'list.html' with data=item %}{% 结束为 %}

结果如下:

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

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

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

解决方案

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

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

{% nospaces %}<强>你好这是文字{% 没空间了 %}

渲染

<strong>你好,这是文本</strong>

I'm using django template to render my webpage. In the process of unrolling the recursive tree something strange happens (and spaceless tag doesn't help).

This is my recursive template:

index.html:

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

        </div>

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



    </li>

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

</ul>

and list.html (as a recursive part):

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

Here is the result:

The html content of file which had been read as a content of html-file using open("index.html", 'r').read() was extracted as a text, not 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>

And also I have strange whitespaces between the elements:

How to avoid this strange behavior? Thank you!

解决方案

{% spaceless %} removes only whitespace between tags, not in text. It is described in docs: https://docs.djangoproject.com/en/2.0/ref/templates/builtins/#spaceless

If you want remove whitespaces also in text you can use custom template tag like this https://gist.github.com/martinsvoboda/1bf965a8c6037c0fe1a88d89ea822df6. Usage:

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

Renders

<strong>Hello this is text</strong>

这篇关于如何避免 django 模板中出现奇怪的空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆