问题描述
我使用django模板,为了可读性,我有类似于以下内容的HTML:
I am using django templating, and for readability I have html that looks similar to the following:
{% if some_variable %}
text
{% else %}
nothing exists here
{% endif %}
{% for item in set %}
{% if forloop.first %}
...etc...
它在运行时转换为以下html,其中包括多个空格和返回:
It converts to the following html at runtime, which includes tons of whitespace and returns:
text
<div>
<li
class='some_class
>
some text
</li>
</div>
etc...
某些页面甚至可以运行到〜3000行html当查看页面源代码。
Some pages even run to ~3,000 lines of html when viewing the page source.
有没有工具在运行时压缩这个html?
Is there a tool to compress this html at runtime? What about a tool to remove extra line breaks?
推荐答案
对于一些背景,这是有意做的,因为Django的模板引擎当前不关心在标签被剥离之后评估为空白的线的消毒线路,并且这样做将在服务响应中带来一些次要的性能损失,因为它涉及评估所呈现的模板的完整内容的后处理步骤。
For a bit of background, this is done intentionally, since Django's templating engine currently doesn't care about sanitizing lines that evaluate to blanks after the tags get stripped out and doing so will incur some minor performance penalties in serving the response, since it involves a post-processing step that evaluates the full contents of the rendered template.
仍然,如果您需要一个快速解决方案,我建议您使用响应中间件,将从文本响应中删除伪造空白。它是相当快速和直接,采用正则表达式匹配像模板引擎本身。一个更加税务,但强大的选择将部署一个响应中间件,利用一个HTML偏好,如果你真的关心穷人仍然读取原始响应。
Still, if you need a quick solution, I suggest you employ the StripWhitespaceMiddleware
response middleware that'll remove spurious whitespaces from textual responses. It's pretty fast and straightforward, employing regular expression matching like the templating engine itself. A more taxing, but powerful alternative would be deploy a response middleware that utilizes an HTML prettifier, if you really care about the poor human beings still reading raw responses.
这篇关于压缩/缩小动态html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!