最後我發現問題是由於在編碼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
或home.html
上使用{%spaceless%} {%endspaceless%},但這不能解決問題,多餘的空格不是由於html標記之間的空格或\ n造成的。
Django 3.3?哇... – iMom0
你當然應該得到一個獎勵..當其他人都在爲1.6和1.7版本苦苦掙扎的時候使用django 3.3 .. –
讓我感到尷尬,因爲我有這樣一個錯字,我想昨天我被這個小但嚴重的問題耗盡了。 AswinMurugesh – TonyTony