2014-01-18 33 views
2

我使用Django的模板,它內置extends標籤,我並沒有把太多的代碼,只是一個導航欄,但我在頂部得到額外的空間瀏覽器,並且無法在Chrome開發人員工具中進行追蹤。這額外的空間仍然存在,就算了,我不喜歡這樣的:Django的模板擴展標記添加額外的空間,在上面

# 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" %} 

然後渲染的文件仍然有這個問題。我使用 Django3.3 的Python 3.3 Django1.6。

這真的很奇怪。

+1

Django 3.3?哇... – iMom0

+0

你當然應該得到一個獎勵..當其他人都在爲1.6和1.7版本苦苦掙扎的時候使用django 3.3 .. –

+0

讓我感到尷尬,因爲我有這樣一個錯字,我想昨天我被這個小但嚴重的問題耗盡了。 AswinMurugesh – TonyTony

回答

6

最後我發現問題是由於在編碼UTF-8 BOM。

我在Windows7上使用Django1.6,Python3.3。我的文本編輯器是Notepad ++,我用UTF-8編碼保存文件。默認情況下,UTF-8以字節順序標記(BOM)保存。這是影響模板渲染的原因,至少對於extendsinclude的標記是如此。比方說,我把它放在一個例子:

# 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.htmlhome.html上使用{%spaceless%} {%endspaceless%},但這不能解決問題,多餘的空格不是由於html標記之間的空格或\ n造成的。

+1

謝謝!如果您要在Visual Studio中保存,請在保存時使用西歐(Windows)代碼頁1252編碼 –

1

Django最新版本是1.7不是3.3,您的第一個代碼註釋將是base.html而不是base.py

,因爲你有你的base.html文件留出空間,你有這個額外的空間。刪除您的base.html文件的頂部額外空間。

0

首先,你可能有Django的1.7和Python 3.3,因爲Django的3.3不存在(並將會在未來十年唯一:-)也許存在)

其次,多餘的空格都存在於HTML因爲Django除了模板中的標籤之外還保留着一切。所以,如果你有這樣的一個模板:

{% load static cache compress %} <!-- <- You have here a \n to create a new line --> 
{% block htmlheader %} 
<!DOCTYPE html> 
<html lang="fr"> 
    <head> 
     .... 

渲染將解釋的部份{% load %}標籤,在渲染HTML頁面中刪除它(實際上不包括它),並繼續解析內容。與{% block %}標記具有相同的行爲,這也會產生\n。結果將是

<!-- A blank line due to the load tag --> 
<!-- A second blank line due to the block tag --> 
<!DOCTYPE html> 
<html lang="fr"> 
    <head> 
     .... 
+0

所以我超越了當前的技術,甚至無法想象Django如何在3.3中看起來......感謝版本和答案,但我發現塊標記對\ n或空間不敏感。這是由於Unicode的BOM,我把它放在一個答案。 – TonyTony