Newsletter
TechAnV Blog
Get updates on security engineering, Rust, eBPF, and DevSecOps. No spam, unsubscribe anytime.
Check your inbox and click the confirmation link to complete your subscription.
Running Prettier against Django or Jinja templates#
I really like auto-formatting tools like Black. I’ve been hoping to find one that works with Django and Jinja templates for years.
Today I managed to get excellent JavaScript Prettier formatter to run against a Jinja template file using the prettier-plugin-jinja-template plugin by David Odenwald.
I had a bit of a fiddle getting it to work because I’m still not fluent in npm/npx, but the recipe I used was the following.
-
Install
prettierandprettier-plugin-jinja-templatein a directory somewhere. This command will create apackage.jsonandpackage-lock.jsonand a a wholenode_modules/folder - the full install adds up to 8.4M:Terminal window 1npm i prettier prettier-plugin-jinja-template -
In that directory run this command:
Terminal window 1npx prettier --plugin=prettier-plugin-jinja-template \2--parser=jinja-template \3--write path/to/your/template.htmlThe
--writeoption will rewrite the template in place.
I first tried using npm i -g prettier prettier-plugin-jinja-template to install the application once, globally, but I couldn’t work out how to get the plugin working that way.
Instead, I’ve added it to my path another way. I already have a ~/.local/bin/ directory that is on my $PATH, so I ran the npm i command from above in that folder and then added this script there, in a file called pretty-templates.sh (created with the help of Claude):
1#!/bin/bash2
3# Check if at least one argument is provided4if [ $# -eq 0 ]; then5 echo "Error: At least one argument is required."6 exit 17fi8
9# Store the current directory10original_dir=$(pwd)11
12# Change directory to ~/.local/bin/13cd ~/.local/bin/ || exit14
15# Convert all paths to absolute paths16args=()17for arg in "$@"; do18 args+=("$original_dir/$arg")19done20
21# Run the prettier command with the absolute paths22npx prettier --plugin=prettier-plugin-jinja-template \23 --parser=jinja-template \24 --write "${args[@]}"Now I can run that command from anywhere on my computer:
1prettier-templates.sh templates/team_backups.htmlAlternatives#
Jeff Triplett pointed me to two pure Python alternatives: