Automatic formatting of Django templates

Does anyone here autoformat their Django template files? If so, do you have suggestions for an autoformatting tool to use?

I wish I could use Prettier, but they have a ticket for supporting Django (and j2 and similar) templates sitting open and waiting for someone to implement it :frowning:

4 Likes

I sadly do not, I think the rise of auto-formatters is recent enough it has sort of passed them by. Would love to see it, though.

1 Like

I feel like the challenge is going to be building a parser that understands the semantics of Djangoā€™s template language and HTML at the same time, given the myriad weird ways the two can be interspersed.

I have some ideas, but lack an in-depth knowledge of how the existing tools in the space work. I really want to dive in and learn and experiment, but the last thing I need right now is another side project, no matter how much I want to :laughing:

I have looked into this repeatedly in the past, because Iā€™m frustrated with my inconsistent HTML files. All existing solutions out there do not seem to support Jinja/Django style markup in any meaningful way, and mangle template files a s a result. Iā€™d be very happy to see any solution, but yeah ā€“ itā€™s not going to be easy.

1 Like

Hi! I wonder if you could use code from a code syntax file? Thereā€™s a pretty good sublime text package that can handle Django templates.

Iā€™m not sure if that would offer auto formatting, at least not to the extent of something like Black or Prettier; I think text editor syntax files only really do lexing and some basic indentation rules. Unless the relevant ST package offers formatting as a built-in feature?

I had a go at building something the other week, and decided after an hour or so that it required more expertise and time that I was able to give it :frowning:

1 Like

Has anyone managed to find anything suitable for VS Code? Would love to use autoformatting for Django templates.

I switched from PyCharm to VSCode (and think it truly worths it), but the only thing Iā€™m still struggling with is this Django template formatting.

An ugly workaround is to use PyCharm command line formatting tool.
But each formatting action takes 5 seconds, and of course itā€™s not a standalone tool, you need PyCharm installed locally. I canā€™t name this a ā€œsolutionā€.

@andrewgodwin Iā€™m questioning myself: would an official VS Code Django plugin be something impossible to develop internally in Django teams?

My thoughts about this:

  • VS Code is becoming a ā€œno-brainer choiceā€ code editing tool for many people. As a personal opinion, I see no point using PyCharm today except for a Django project. But dealing with two IDEs is painful.

  • Even if one disagree about the statement above, I donā€™t see a Django beginner spending money to buy PyCharm pro Edition (the free edition has no real Django support), especially because VS Code is free. Which means the first experience this beginner will get with Django templates will be ā€¦ not perfect.

  • Many developers love Django, but they are and more and more used to a top-level tooling experience, especially in JS community. Auto-formatters are getting really mainstream with tools like Prettier. I have the feeling that many developers could decide NOT using Django templates, just because front-end development experience is way better with tools like Vue.js, almost out of the box.

  • Some modern frameworks come with their own official plugin (Iā€™m thinking of TailwindCSS Intellisense) and itā€™s amazing. It just works. To me, itā€™s truly more valuable when itā€™s official. It brings trust, and removes the need of choosing among 10 different plugins that overlaps themselves.

I know it takes huge work, but Iā€™m curious to hear your point of view about the prioritization of such work, compared to classic features.

2 Likes

I think having a proper plugin would be lovely, but itā€™s not something the current core team has the time or (for most of us) the skillset to develop; a template auto-formatter, in particular, would have to be authored somewhat from scratch.

This is the sort of thing, though, that could be developed outside of the Django core code and then officially recommended or that sort of thing. I do think itā€™s worth it, I just donā€™t think itā€™s something we can justā€¦ do.

3 Likes

The only solution I found this video on YouTube.

ā€œhe does not speak Englishā€ but it would not matter it all about install 3 extensions, and it will autocomplete Django template and HTML too.

Iā€™m not sure if Iā€™m missing something hereā€”as best I can tell, that videoā€™s only about autocompletion and snippets, rather than auto formatting :frowning:

1 Like

What I did, I use Perrier to formal HTML then I switch to Django and write all my code if the code need more format I switch back to HTML, that is the best thing till now for me

prettydiff does a good job. hope it helps anyone, also good for other template languages like twig etc.

prettydiff beautify source:<your file>

djhtml looks promising for cleaning up the formatting of Django template code.

5 Likes

Update, djhtml cleans up indentation, but not other kinds of formatting.

3 Likes

I had the same pain and couldnā€™t find anything working well. There was an extension for sublimetext, but it only worked sometimesā€¦ So I put together an experimental one called djLint, which lints templates and can also format complete html template docs.
Assuming you use a custom file extension of ā€œhtml.djā€, you can run

djlint /path --extension=html.dj --check

to see what it thinks about your files.

Iā€™m here to +1 djhtml. I have been using it for a few months and it does enough safely, that itā€™s been auto-formatting all of my projects ever since.

If indentation is what you are looking for then itā€™s worth checking out.

9 Likes

Thing is an autocomplete takes care of tags, so one is not very likely to have a bad indentation, rather they donā€™t want to have to indent manually in the first place as you are auto dropping the tags in. The flow of tag completion + save ā†’ autoformat (even if just indentation) is great. djhtml will only fix bad indentation, not format to a prescribed indentation for you.

Here is whatā€™s working best for me currently within VS Code:

  • I installed djhtml, as advised.
  • To run it on file saving, I installed runOnSave extension and configured it to target Django HTML files only:
"emeraldwalk.runonsave": {
    "commands": [
        {
            "match": ".*/templates/.*\\.html$", // only in templates dir
            "cmd": "djhtml -i ${file} -t 2"
        },
    ]
},

Used in conjunction with this extension (syntax color and snippets), this makes using django templates ok imo (not perfect, but acceptable).

I guess a future improvment of this workflow could be to build a VS Code formatter extension that embbed djhtml, rather than installing a python package. Any volonteer ? :slight_smile:

For now it seems these 3 tools are used and appreciated by the community:

Is anyone able to provide quick comparison between them? Otherwise Iā€™ll test all of them by myself.
Thanks.

2 Likes