【问题标题】:How to remove spaces and empty lines from HTML in Django?如何从 Django 中的 HTML 中删除空格和空行?
【发布时间】:2015-01-05 14:16:11
【问题描述】:

我使用Python 3.4 + Django 1.7.1Eclipse - PyDev,并使用AcroEdit 编辑HTML。

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

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

# -*- 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>

(如您所见,内容对象有名称和子项)

所以,custom_tag 是一个递归标签,给出了一个树结构,以&lt;div&gt; 层次结构表示。

但是当我使用它时,输出的 HTML 有很多空格和空行,如下所示:

我试过{% spaceless %}{% endspaceless %},但是没用。

我认为这是因为我使用缩进来增加代码的可读性。但我想保持我对缩进的编码风格。

我该如何解决这个问题?

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    我遇到了完全相同的问题。您希望拥有干净的模板 html 文件,您可以轻松阅读(您得到的),同时您希望在渲染时拥有人类可读的 html。

    因此,您不会对将 templatetag.html 文件更改为类似旧的 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 并将其重写为更整洁的东西。

    您可以在PyEvolve website 上找到您想要的内容。它的作用基本上是:

    1. 使用 BeautifulSoup 解析您的 HttpResponse html
    2. 美化它(用很酷的缩进)
    3. 将其作为新的 HttpResponse 返回

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

    【讨论】:

      猜你喜欢
      • 2011-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-08
      相关资源
      最近更新 更多