Minify HTML output from Flask application with Jinja2 templates

前端 未结 7 940
鱼传尺愫
鱼传尺愫 2021-02-02 11:24

Is there a Flask or Jinja2 configuration flag / extension to automatically minify the HTML output after rendering the template?

7条回答
  •  死守一世寂寞
    2021-02-02 11:32

    Modifying @Bletch answer for the latest version of htmlmin.

    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

    The minified html will still have some spaces between the tags. If we want to remove that, then remove_empty_space =True attribute needs to be added while the template is rendered.

    return htmlmin.minify(rendered_html, remove_empty_space =True)
    

    https://htmlmin.readthedocs.io/en/latest/reference.html

提交回复
热议问题