Minify HTML output from Flask application with Jinja2 templates

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

    I use the following decorators

    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
    

    And simply wrapped the default render_template function like so

    if app.debug:
        flask.render_template = prettify(flask.render_template)
    else:
        flask.render_template = uglify(flask.render_template)
    

    This has the added benefit of being auto added to the cache, since we don't actually touch app.route

提交回复
热议问题