Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Minify HTML output from Flask application with Jinja2 templates

Tags:

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

like image 690
Alexander Avatar asked Nov 27 '12 15:11

Alexander


People also ask

Which of the following statements is used to inherit a template to a new HTML page?

Using extends we can inherit templates as well as variables.

How do I render a Python template?

render_template is a Flask function from the flask. templating package. render_template is used to generate output from a template file based on the Jinja2 engine that is found in the application's templates folder. Note that render_template is typically imported directly from the flask package instead of from flask.


3 Answers

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 
like image 85
hamidfzm Avatar answered Sep 28 '22 10:09

hamidfzm


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.

like image 39
olly_uk Avatar answered Sep 28 '22 11:09

olly_uk


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

like image 28
Ethan McCue Avatar answered Sep 28 '22 10:09

Ethan McCue