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:

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.

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