gpt4 book ai didi

python - 如何避免 django 模板中出现奇怪的空格?

转载 作者:行者123 更新时间:2023-12-02 21:17:34 26 4
gpt4 key购买 nike

我正在使用 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>

结果如下:

strange behavior

使用 open("index.html", 'r').read() 作为 html 文件的内容读取的文件的 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>

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

enter image description here

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

最佳答案

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

关于python - 如何避免 django 模板中出现奇怪的空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29675216/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com