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

大兔子大兔子 提交于 2019-12-07 12:56:42

问题


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:

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?


回答1:


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.



来源:https://stackoverflow.com/questions/27781379/how-to-remove-spaces-and-empty-lines-from-html-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!