Minify HTML output from Flask application with Jinja2 templates

Alexander picture Alexander · Nov 27, 2012 · Viewed 12.5k times · Source

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

Answer

hamidfzm picture hamidfzm · Oct 1, 2014

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