Django 模板扩展标签在顶部添加了额外的空间

标签 django templates

我正在使用带有内置 extends 的 Django 模板标签,我没有在里面放太多代码,只是一个导航栏,但是我在浏览器顶部获得了额外的空间,而这在 chrome 开发人员工具中无法追踪。额外的空间仍然存在,即使我是这样的:

# base.html

<!doctype html>
<html>
<head>
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static "css/layout.css" %}" />
</head><body>
    <div><p>something here.</p>
    </div>    
</body>
</html>

然后我只用一行代码扩展它:
# home.html

{% extends "base.html" %}

然后渲染的文件仍然有这个问题。我在 Django1.6 中使用 Django3.3 Python 3.3。

这真的很奇怪。

最佳答案

最后我发现问题是由于编码中的 UTF-8 BOM。

我在 Windows7 上使用 Django1.6、Python3.3。我的文本编辑器是 Notepad++,我以前用 UTF-8 编码保存文件。默认情况下,UTF-8 与字节顺序标记 (BOM) 一起保存。正是这个影响了模板的渲染,至少对于 extends 的标签来说是这样的。和 include .比方说,我把它放在一个例子中:

# home.html
{% extends "base.html" %}

{% block content%}
    {% include "a.html" %}
    {% include "b.html" %}
{% endblock %}


# base.html
<!doctype html>
<html>
<head>
<!-- This file saved with encoding UTF-8, which is by default with BOM.-->
</head>
<body>
    <div><p>something here, base.</p></div>
    {% block content%}{% endblock %}    
</body>
</html>


# a.html
<p>a.html, saved in utf-8 without BOM. </p> 


# b.html
<p>b.html, saved in utf-8, which is by default with BOM in Notepad++.</p> 

输出是什么?它看起来像这样
___________ ( top of your browser )
            ( extra space on top, due to extended file `base.html` is with BOM )
something here, base.
a.html, saved in utf-8 without BOM. (no extra space above the content of a.html)
            ( extra space on top, due to included file `b.html` is with BOM )
b.html, saved in utf-8, which is by default with BOM in Notepad++.

所以,基本上,对于模板加载的任何文件,如果它带有 BOM,那么渲染的 html 将在其部分顶部添加额外的空格。因此,请记住使用 UTF-8 保存所有文件,而无需 BOM。

注意:我之前曾尝试在我的 base.html 上使用 {% spaceless %}{% endspaceless %}或 home.html ,但这不能解决问题,额外的空格不是由 html 标签之间的空格或\n 引起的。

关于Django 模板扩展标签在顶部添加了额外的空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21204834/

相关文章:

javascript - AJAX 调用后使用 django 变量填充下拉列表

jquery - Django:重建通过 $.post 发送的结构化参数

c++ - G++ 模板实例化导致 "Undefined reference to"错误

c++ - 如何在任意依赖类型上专门化模板

c++ - 可变参数模板类型解包到映射键中

python - Django 模型中的 Post 方法

django - 在 Django 中,如何确定请求是否已被取消?

python - Django 1.8 和 Gmail - SMTPAuthenticationError 用户名和密码不被接受

c++ - initializer_list 和 move 语义

templates - Liferay 速度模板和结构。得到 child 的 child ?