TIL - Prettier Django Templates
Formatting Django templates has been a pet peeve of mine. The "big" player in that area seems to be djlint, but I just could not really get over how it formatted my files, especially when I'm used to the formatting in the Javascript/JSX world. Also, it is quite slow for larger files.
Since VS Code is my Python editor of choice and it is extremely easy to test different plugins, I tried a few and in the end settled for the built-in formatter, which seemed to have the best support for the Django/Jinja template syntax, namely {{ }} and {% %}.
As it sometimes happens, I should have just put the time in to learn a tiny bit about Prettier, its plugins and how to configure it. Hell, I even tried the one integrated into VS code, but out-of-the-box the result weren't satisfactory, so I ditched it. In the end it took just a few minutes, but I think this will be my setup for the time being.
The Setup
Without further ado, here's the setup.
1. Install prettier
Install prettier and the required plugins at a suitable place. I just installed them in my project root. Of course this will add an "ugly" node_modules to your root, but I don't mind that. Since I'm also using TailwindCSS for styling, I'm gonna need a plugin for that, too.npm install prettier prettier-plugin-tailwindcss prettier-plugin-jinja-template
2. Configure prettier
Add a .prettierrc file somewhere suitable. Again, I chose my projects root directory, but you can choose any location you like. Of course then you'll have to configure VS Code some more.
My file looks like this:
1{
2 "plugins": ["prettier-plugin-tailwindcss", "prettier-plugin-jinja-template"],
3 "singleAttributePerLine": true,
4 "overrides": [
5 {
6 "files": "*.html",
7 "options": {
8 "parser": "jinja-template"
9 }
10 }
11 ]
12}
3. Configure VS Code
I added the following settings to my projects .vscode/settings.json:
1{
2 "prettier.configPath": ".prettierrc",
3 "prettier.enable": true,
4 "html.format.enable": false
5}
4. Never manually format Django templates again
Of course this is still not perfect. I guess, I'd like it more if the extremely long class-lists that sometimes come with tailwind would be broken over several lines, but it seems that this cannot be configured.
And that's a good thing! In my experience, it's not worth loosing any sleep about a line not wrapping.