How to minify HTML in Flask using Flask-Minify
What does it mean to minify HTML?
To minify the code is to minimize the code present in webpages. This will:
- Remove extra spaces
- Remove comments
- Crunch variable names
Why minify HTML?
Though comments and spaces help in the readability of the code, they will increase the size of an application. As a result, it increases the network’s bandwidth requests.
Minifying the HTML will:
- Load the webpage faster
- Reduce file size and bandwidth
- Improve UX and SEO
How to minify HTML in Flask
Flask-Minify library helps us to minify HTML, CSS, and JavaScript files.
Steps:
- Install it with PIP:
pip install Flask-Minify
- There are two ways to set up:
- Minify every request. This will minify every request that returns from the application.
from flask import Flask
from flask_minify import minify
app = Flask(__name__)
minify(app=app, html=True, js=True, cssless=True)
- Minify only decorated routes. This will minify only routes that are specified. Others will be served normally.
from flask import Flask
from flask_minify import minify, decorators
app = Flask(__name__)
minify(app=app, passive=True)
@app.route('/')
@decorators.minify(html=True, js=True, cssless=True)
def home():
return """
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h2>This is a Heading</h2>
<p>This is a paragraph.</p>
</body>
</html>
""