【发布时间】:2012-11-15 06:26:56
【问题描述】:
是否有 Flask 或 Jinja2 配置标志/扩展来在渲染模板后自动缩小 HTML 输出?
【问题讨论】:
-
@SeanVieira 它实际上删除了许多有用的空格.. 所以它破坏了你的 HTML ..
标签: python web-applications flask wsgi jinja2
是否有 Flask 或 Jinja2 配置标志/扩展来在渲染模板后自动缩小 HTML 输出?
【问题讨论】:
标签: python web-applications flask wsgi jinja2
找到了一个更好的方法来做到这一点。您可以使用此方法缩小所有页面:
from flask import Flask
from htmlmin.main import minify
app = Flask(__name__)
@app.after_request
def response_minify(response):
"""
minify html response to decrease site traffic
"""
if response.content_type == u'text/html; charset=utf-8':
response.set_data(
minify(response.get_data(as_text=True))
)
return response
return response
【讨论】:
看看这里https://github.com/cobrateam/django-htmlmin#using-the-html_minify-function
我意识到它主要用于 django,但我认为该示例显示了如何使用此项目代码通过烧瓶视图执行您想要的操作。
【讨论】:
setup.py 文件仍然需要 Django。
我使用以下装饰器
import bs4
import functools
import htmlmin
def prettify(route_function):
@functools.wraps(route_function)
def wrapped(*args, **kwargs):
yielded_html = route_function(*args, **kwargs)
soup = bs4.BeautifulSoup(yielded_html, 'html.parser')
return soup.prettify()
return wrapped
def uglify(route_function):
@functools.wraps(route_function)
def wrapped(*args, **kwargs):
yielded_html = route_function(*args, **kwargs)
minified_html = htmlmin.minify(yielded_html)
return minified_html
return wrapped
然后像这样简单地包装了默认的 render_template 函数
if app.debug:
flask.render_template = prettify(flask.render_template)
else:
flask.render_template = uglify(flask.render_template)
这具有自动添加到缓存中的额外好处,因为我们实际上并没有触及 app.route
【讨论】:
我已经编写了一个烧瓶扩展来实现这个目的。您可以使用 pip install flask-htmlmin 安装它,源代码位于 https://github.com/hamidfzm/Flask-HTMLmin 。希望对你有用。
【讨论】:
使用装饰器。
from htmlmin.decorator import htmlmin
@htmlmin
def home():
...
或者你可以使用:
re.sub(r'>\s+<', '><', '<tag> </tag>') # results '<tag></tag>'
【讨论】:
a <b>big</b> <i>fat</i> <s>edit</s> here 会导致输出 a <b>big</b><i>fat</i><s>edit</s> here - 空格已被破坏。
为了扩展来自@olly_uk 的答案和@Alexander 的评论的有用性,似乎django-htmlmin 扩展现在设计用于与Django 以外的框架一起使用。
从文档here,您可以在 Flask 视图中手动使用 html_minify 函数,如下所示:
from flask import Flask
from htmlmin.minify import html_minify
app = Flask(__name__)
@app.route('/')
def home():
rendered_html = render_template('home.html')
return html_minify(rendered_html)
【讨论】:
re 模块做到这一点:return sub(r'\s{2,}|[\r\n]', '', render_template('blah.html'))... 是什么让 minify 如此特别?
为最新版本的 htmlmin 修改 @Bletch 答案。
from flask import Flask
import htmlmin
app = Flask(__name__)
@app.route('/')
def home():
rendered_html = render_template('home.html')
return htmlmin.minify(rendered_html)
https://htmlmin.readthedocs.io/en/latest/quickstart.html
缩小后的 html 在标签之间仍然会有一些空格。如果我们想移除它,则需要在渲染模板时添加remove_empty_space =True 属性。
return htmlmin.minify(rendered_html, remove_empty_space =True)
【讨论】: