Auto-Format HTML Templates in Django with VSCode

Problem:

When writing HTML templates for the Django Python framework, you want to use Visual Studio Code’s auto formatting features. However, when you activate the auto-format functionality, VSCode complains that there is no formatter available for such HTML files:

“There is no formatter for ‘django-html’ files installed.”

Solution:

First, install the beautify extension.

Then, open the settings.json by pressing SHIFT - CMD - P and enter “Open Settings (JSON)”:

Next, add the following block to your settings.json:

"files.associations": {
    "**/*.html": "html",
    "**/templates/**/*.html": "django-html",
    "**/templates/**/*": "django-txt",
    "**/requirements{/**,*}.{txt,in}": "pip-requirements"
},
"emmet.includeLanguages": {
    "django-html": "html"
},
"beautify.language": {
    "html": [
        "htm",
        "html",
        "django-html"
    ]
}

Save the changes and go back to your HTML template – you should now be able to format the HTML code automatically by pressing SHIFT - OPTION - F.

Bernhard Knasmüller on Software Development