How to remove spaces and blank lines from HTML in Django?
I am using Python 3.4
+ Django 1.7.1
c Eclipse - PyDev
and I am using AcroEdit
HTML to edit.
I think it AcroEdit
uses two soft spaces for padding.
I created my own template tag named custom_tag
in custom_tag_library.py
, for example:
# -*- coding: utf-8 -*-
from django import template
from _ast import Num
register = template.Library()
@register.inclusion_tag('custom_tag.html')
def custom_tag(content):
return {'content': content, 'children': content.children.all()}
and for custom_tag.html
:
{% load custom_tag_library %}
<div class = 'a'>
{{ content.name }}
{% if children %}
<div class = 'b'>
{% for child in children %}
{% custom_tag child %}
{% endfor %}
</div>
{% endif %}
</div>
(As you can see, the content object has a name and children)
So, custom_tag
is a recursive tag that gives the tree structure represented in the hierarchy <div>
.
But when I use this, the output HTML has a lot of spaces and blank lines:
I tried {% spaceless %}
{% endspaceless %}
it but it doesn't work.
I think this appears because I am using indentation to improve the readability of my codes. But I want to keep my coding style regarding indentation.
How can I fix this?
source to share
I have exactly the same problem. You want to have clean templated html files that you can easily read (which you have), and you want human readable html to be available at the same time when rendering it.
So you won't be happy with the decision to change the templatetag.html file to something like this, which looks like the old php spaghetti:
{% load custom_tag_library %}
<div class = 'a'>{{ content.name }}
{% if children %}<div class = 'b'>
{% for child in children %}{% custom_tag child %}{% if not forloop.last %}
{% endif %}{% endfor %}
</div>{% endif %}
</div>
The second solution (and also the best one) is to have middleware to read and overwrite each HttpResponse with something neater.
You can find exactly what you want on the PyEvolve website . Mainly:
- Parse httml HttpResponse with BeautifulSoup
- Provide it (with cold indentation)
- Return it as a new HttpResponse
But with this solution, you may have a performance issue.
source to share