Minify HTML output from Flask application with Jinja2 templates

前端 未结 7 942
鱼传尺愫
鱼传尺愫 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:45

    Found a better way to do this. You can minify all your pages with this method:

    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
    

提交回复
热议问题