DjHTML: Django/Jinja Template Indenter
DjHTML is a pure-Python Django/Jinja template indenter without external dependencies. It formats mixed HTML/CSS/JavaScript templates that incorporate Django or Jinja template tags. Similar to tools like Black, DjHTML acts as an indenter, primarily adjusting leading whitespace to ensure consistent indentation, rather than performing comprehensive code reformatting. It is actively maintained with a regular release cadence, with the latest version being 3.0.11.
Warnings
- breaking Support for Python 3.8 was dropped in DjHTML 3.0.7. Users on Python 3.8 or older must upgrade their Python version to 3.9 or higher to use recent DjHTML versions.
- breaking The `-q` or `--quiet` command-line option was removed in version 3.0.3. Output is now directed to stderr, allowing users to redirect stderr to `/dev/null` for quiet operation.
- gotcha On Windows, DjHTML highly advises setting the `PYTHONUTF8` environment variable to 1 to ensure correct handling of UTF-8 encoding, especially with legacy code pages.
- gotcha DjHTML is an *indenter*, not a full *formatter*. It will only add or remove whitespace at the beginning of lines to correct indentation; it will not insert newlines, reorder attributes, or fix malformed HTML. Its goal is to correctly indent already well-structured templates.
- gotcha When used as a `pre-commit` hook, if DjHTML modifies files, `git commit` will fail. You must `git add` the changes and re-commit, or use `SKIP=djhtml git commit` to bypass the hook for that commit.
Install
-
pip install djhtml
Quickstart
mkdir djhtml_test
cd djhtml_test
echo '{% if user.is_authenticated %}<div class="welcome">Hello, {{ user.username }}!</div>{% else %}<a href="/login/">Login</a>{% endif %}' > template.html
# Indent a single file
djhtml template.html
# Verify changes
cat template.html
# Indent all HTML files in the current directory and subdirectories
djhtml .
# Example of checking without modifying (exit code 1 if changes are needed)
djhtml --check template.html