我正在使用带有内置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" %}
然后渲染的文件仍然有这个问题。我正在将 Django3.3和 Python 3.3与Django1.6配合使用。
真的很奇怪
最后我发现问题是由于编码中的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的文件。
注:我曾尝试更早使用{%spaceless%} {%endspaceless%}我base.html
还是home.html
,但是这不能解决问题,多余的空格不是由于空格或\ n HTML标记之间。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句