Analysis
Analysis

Reputation: 250

How to remove spaces and empty lines from HTML in Django?

I use Python 3.4 + Django 1.7.1 with Eclipse - PyDev and I use AcroEdit to edit HTML.

I think AcroEdit uses two soft spaces for indent.

I made a custom template tag named custom_tag in custom_tag_library.py like:

# -*- 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, content object has name and children)

So, custom_tag is a recursive tag gives a tree structure represented in <div> hierarchy.

But when I use this, the output HTML has many spaces and empty lines like this:

Google Chrome DOM Inspector

I tried {% spaceless %} {% endspaceless %}, but it doesn't work.

I think this appears because I use indents to increase readability for my codes. But I want to maintain my coding style about the indentation.

How can I fix this?

Upvotes: 4

Views: 2318

Answers (1)

Spoutnik16
Spoutnik16

Reputation: 864

I've got exactly the same problem. You want to have clean template html files, that you can easily read (what you got), and you want at the same time to have human readable html when you render it.

So you won't be happy with the solution of changing your templatetag.html file to something like this, which looks like 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 a middleware to read and rewrite every HttpResponse to something more tidy.

You can find exactly what you want on the PyEvolve website. What it does is basically :

  1. Parse your HttpResponse html with BeautifulSoup
  2. Prettify it (with cool indent)
  3. Return it as the new HttpResponse

But with this solution, you might have performence issue.

Upvotes: 3

Related Questions