Automatic HTML minification for Jinja2 templates.
- Zero runtime overhead: Minification happens once at load time, not on every render
- Smaller HTML: Reduced bandwidth and faster page loads
- Drop-in compatibility: Works with any Jinja2 loader (Flask, Django, FastAPI, etc.)
- Broad Python support: Compatible with Python 3.9+
- Semantic Versioning: Predictable, reliable updates
- Zero-Clause BSD: Public domain, use freely anywhere
pip install jinja2-htmlmin
from jinja2 import Environment, FileSystemLoader
from jinja2_htmlmin import minify_loader
# Wrap any Jinja2 loader
# See https://htmlmin.readthedocs.io/en/latest/reference.html for options
env = Environment(
loader=minify_loader(
FileSystemLoader("templates"),
remove_comments=True,
remove_empty_space=True,
remove_all_empty_space=True,
reduce_boolean_attributes=True,
)
)
# Rendered HTML is automatically minified
html = env.get_template('index.html').render(title='My Page')
- Template loads normally through your existing loader
- Jinja2 syntax is temporarily protected during minification
- HTML content is minified using htmlmin2
- Jinja2 syntax is restored and template compiles as usual
- Jinja2's built-in caching means this happens only once per template