# jinja2-htmlmin

[![PyPI - Python Version](https://shields.monicz.dev/pypi/pyversions/jinja2-htmlmin)](https://pypi.org/p/jinja2-htmlmin)
[![Liberapay Patrons](https://shields.monicz.dev/liberapay/patrons/Zaczero?logo=liberapay&label=Patrons)](https://liberapay.com/Zaczero/)
[![GitHub Sponsors](https://shields.monicz.dev/github/sponsors/Zaczero?logo=github&label=Sponsors&color=%23db61a2)](https://github.com/sponsors/Zaczero)

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**](https://semver.org): Predictable, reliable updates
- [**Zero-Clause BSD**](https://choosealicense.com/licenses/0bsd/): Public domain, use freely anywhere

## Installation

```bash
pip install jinja2-htmlmin
```

## Quick Start

```python
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](https://github.com/wilhelmer/htmlmin)
4. Jinja2 syntax is restored and template compiles as usual
5. Jinja2's built-in caching means this happens only once per template
