最后我发现问题是由编码中的UTF-8 BOM引起的。
我使用Django1.6,Python3.3,在Windows7上。我的文本编辑器是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>
</head>
<body>
<div><p>something here, base.</p></div>
{% block content%}{% endblock %}
</body>
</html>
以及
<p>a.html, saved in utf-8 without BOM. </p>
和
<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
或home.html
上使用{% spaceless %}{% endspaceless %},但这不能解决问题,额外的空格不是由HTML标签之间的空格或\n引起的。