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

☆樱花仙子☆ 提交于 2019-12-05 19:00:50
Spoutnik16

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.

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