VSCode breaks Django template tags with newline

Viewed 992

Problem:

{% extends 'base.html' %} {% block title %} Dashboard {% endblock %} {% block pagetitle %}

becomes

{% extends 'base.html' %} {% block title %} Dashboard {% endblock %} {% block
pagetitle %}

Note that the {% tag %} is being broken with a new line. This causes syntax errors with django templates.

I've tried most top django template extensions and this does not fix the issue.

I've also tried these settings:

    "[html]": {
        "editor.formatOnSave": false,
    },
    "html.format.wrapLineLength": 0,
    "html.format.enable": false,
    "prettier.disableLanguages": ["html"] 

Desired Behavior:

  1. Automatically format *.html files, while preserving django template tags, not breaking them up with newlines.
  2. Sub-optimal (but acceptable) behavior: don't format *.html files at all.
4 Answers

I had the same issue and the only way I found that solved it is to disable the default HTML formatter. Unfortunately, I did not find a way to make it format Django template tags correctly. You can do the same if you go to VS Code Preferences > Settings > User > Extensions > HTML and uncheck 'Enable/disable default HTML formatter'.

enter image description here

I got it to work by simply adding {{""}} between the {% tag %} that were being broken.

Example:

{% extends 'main/base.html' %} {% block title_block %}Homepage{% endblock%}
{{""}} {%block style_ref_block%}{%endblock%} {{""}} {% block body_block %}

This Didn't work for me.

The hack I found was to set the vscode language to jinja instead of the auto detected html

reference

I've also just experienced vs-code misbehaving on django template tags (i.e. deleting curly braces).

I don't like the idea of disabling HTML formatting just to support templates (i.e. vs-code Preferences/Settings/Extensions/HTML: disable (uncheck) "HTML>Format:Enable"). This is arguably a step backwards, but it does stop vs-code misbehaving.

Instead, I chose to install (vs-code Preferences/Extensions) the 'Django' extension, by Baptiste Darthenay. This was a better way to go, because it works, gracefully, preserves native vs-code HTML formatting, and includes a nice set of django snippits, which saves me keystrokes when embedding template code. Tada!

BTW, before finding Baptiste's awesome extension, I also tried keeping vs-code HTML formatting enabled, AND enabling 'HTML>Format:Templating', which promised to "Honor django and other templating language tags"; it did not.

Related