Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django template extends tag added extra space on top

I am using Django template with the built-in extends tag, I didn't put too much code in it, just a nav bar, but I get extra space on top of the browser, and that can not be traced in chrome developer tools. That extra space still exists, even if, I did like this:

# 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>

and then I extend it with just one line of code:

# home.html

{% extends "base.html" %}

Then rendered file still have this problem. I am using Django3.3 Python 3.3 with Django1.6.

It was really strange.

like image 726
TonyTony Avatar asked Jan 18 '14 13:01

TonyTony


2 Answers

Finally I find the problem was due to UTF-8 BOM in encoding.

I use Django1.6, Python3.3, on Windows7. My text editor is Notepad++, and I used to save files under UTF-8 encoding. By default, UTF-8 is saved with a byte order mark(BOM). It was this that affects the rendering of templates, at least for the tag of extends and include. Let's say, I put it in an example:

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

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

and

# 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>

and

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

and

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

what will be the output? It will look like this

___________ ( 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++.

so, basically, for any file loaded by the template, if it is with BOM, then the rendered html will add extra spaces on top of its section. Therefore, remember to save all the files with UTF-8 without BOM.

Note: I have tried earlier to use {% spaceless %}{% endspaceless %} on my base.html or home.html, but this cannot solve the problem, the extra spaces wasn't due to spaces or \n between html tags.

like image 67
TonyTony Avatar answered Nov 15 '22 05:11

TonyTony


Django most recent version is 1.7 not 3.3, and your first code comment will be base.html not base.py.

You got this extra space because of you have leave space in your base.html file. remove the top extra space of your base.html file.

like image 34
Yogesh dwivedi Geitpl Avatar answered Nov 15 '22 04:11

Yogesh dwivedi Geitpl