如何从 Django 中的 HTML 中删除空格和空行?

2023-12-20

I use Python 3.4 + Django 1.7.1 with Eclipse - PyDev我用AcroEdit编辑 HTML。

I think AcroEdit使用两个软空格进行缩进。

我制作了一个名为的自定义模板标签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>

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

So, custom_tag是一个递归标签,给出了表示为的树结构<div>等级制度。

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

I tried {% spaceless %} {% endspaceless %},但它不起作用。

我认为出现这种情况是因为我使用缩进来提高代码的可读性。但我想保持我关于缩进的编码风格。

我怎样才能解决这个问题?


我也有同样的问题。您想要拥有干净的模板 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 网站 http://blog.christianperone.com/?p=814。它的作用基本上是:

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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何从 Django 中的 HTML 中删除空格和空行? 的相关文章

随机推荐