Skip to content

Zaczero/jinja2-htmlmin

Repository files navigation

jinja2-htmlmin

PyPI - Python Version Liberapay Patrons GitHub Sponsors

Automatic HTML minification for Jinja2 templates.

Why Use This?

  • 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

Installation

pip install jinja2-htmlmin

Quick Start

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')

How It Works

  1. Template loads normally through your existing loader
  2. Jinja2 syntax is temporarily protected during minification
  3. HTML content is minified using htmlmin2
  4. Jinja2 syntax is restored and template compiles as usual
  5. Jinja2's built-in caching means this happens only once per template