如何在Django中从HTML删除空格和空行? [英] How to remove spaces and empty lines from HTML in Django?

查看:266
本文介绍了如何在Django中从HTML删除空格和空行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Eclipse-PyDev中使用 Python 3.4 + Django 1.7.1 code>,我使用 AcroEdit 编辑HTML。

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

我认为 AcroEdit 使用两个软空格进行缩进。

I think AcroEdit uses two soft spaces for indent.

我制作了一个名为 custom_tag 的自定义模板标签在 custom_tag_library.py 中:

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()}

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)

因此, custom_tag 是一个递归标签,它给出了以÷ div> 表示的树结构

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

但是当我使用它时,输出HTML包含许多空格和空行,如下所示:

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

我尝试了 {%spaceless%} {%endspaceless%} ,但这无效。

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.

如何解决此问题?

推荐答案

我遇到了完全相同的问题。您希望拥有干净的模板html文件,可以轻松阅读(获得的内容),并且同时希望在呈现它时具有人类可读的html。

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.

因此,您不会对将templatetag.html文件更改为类似旧php spaghetti的解决方案感到满意:

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>

第二个解决方案(也是最好的解决方案)是拥有一个中间件来读取和重写每个HttpResponse

The second solution (and also the best one) is to have a middleware to read and rewrite every HttpResponse to something more tidy.

您可以在 PyEvolve网站。它的作用基本上是:

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


  1. 使用BeautifulSoup解析HttpResponse html

  2. 美化它(非常酷缩进)

  3. 将其返回为新的HttpResponse

但是使用此解决方案,您可能性能问题。

But with this solution, you might have performence issue.

这篇关于如何在Django中从HTML删除空格和空行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆