Skip to content Skip to sidebar Skip to footer

Minify Html Output From Flask Application With Jinja2 Templates

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

Solution 1:

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_requestdefresponse_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

Solution 2:

Have a look here https://github.com/cobrateam/django-htmlmin#using-the-html_minify-function

I realise it is mainly used for django but the example shows how to use this projects code to do what you want with a flask view, i think.

Solution 3:

I use the following decorators

import bs4
import functools
import htmlmin


defprettify(route_function):
    @functools.wraps(route_function)defwrapped(*args, **kwargs):
        yielded_html = route_function(*args, **kwargs)
        soup = bs4.BeautifulSoup(yielded_html, 'html.parser')
        return soup.prettify()

    return wrapped

defuglify(route_function):
    @functools.wraps(route_function)defwrapped(*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

Solution 4:

I've written a flask extension to achieve that purpose. You can install it using pip install flask-htmlmin and the source is available at https://github.com/hamidfzm/Flask-HTMLmin . Hope it will be useful.

Solution 5:

Use the decorator.

from htmlmin.decorator import htmlmin

@htmlmindefhome():
...

Or you can just use:

re.sub(r'>\s+<', '><', '<tag>   </tag>') # results '<tag></tag>'

Post a Comment for "Minify Html Output From Flask Application With Jinja2 Templates"