skip to content

Fixing autoformatting Django templates in Visual Studio Co

Prettier autoformatting screws up Django html templates in Visual Studio Code. For example, it puts tags on the same line when they shouldn't be. The fix is pretty simple and involves a couple of different formatting extension.

This post consolidates the information I got the information from a couple of SO answers.

  1. Install the Django extension. It will give you some snippets, and syntax higlighting. But most important, it will add the django-html filetype to VSC

  2. Install the Beautify extension. This will replace Prettier for those specific files

  3. Open the User settings, and switch to JSON mode. You will be adding a few settings manually

  4. The files.associations block could be already in your settings. If it isn’t, you need to add it. Otherwise add the following associations to it

    "files.associations": {
      "**/templates/*.html": "django-html",
      "**/*.html": "html"
    },
  5. Tell Beautify about Django templates

    "beautify.language": {
      "html": ["htm", "html", "django-html"]
    },
  6. Replace Prettier with Beautify for Django templates. Note that "prettier.disableLanguages": ["django-html"], is no longer supported by VSC.

    "[django-html]": {
      "editor.defaultFormatter": "HookyQR.beautify"
    },

    You can of course add more settings to that particular block; for example, mine is

    "[django-html]": {
      "editor.defaultFormatter": "HookyQR.beautify",
      "editor.formatOnSave": true,
      "editor.tabSize": 2
    },
  7. If you like emmet, which is now part of VSC by default, also add

    "emmet.includeLanguages": {
      "django-html": "html"
    }

Prior art

I got some of the information from this SO answer and this other SO answer