Search code examples
htmldjangodjango-templatesvisual-studio-code

How to make VSCode format Django templates properly?


I love VSCode on-save auto-format, until it messed up with my template code.

It wrongly formats my django template syntax into one line code (sometimes really long line). So instead of having this code

{% for row in 'ABCDEFGH' %}
<tr>
  {% for col in '123456789012345' %}
    <td>
      {% with forloop.counter|stringformat:"s" as counter %}
        {% with row|add:counter as seat_num %}
          {% if seat_num not in oc_seats %}
            <input type="checkbox" value="{{ row }}{{ forloop.counter }}" name="seats">
          {% endif %}
          <br> {{ seat_num }} 
        {% endwith %}
      {% endwith %}
     </td>    
   {% endfor %}
</tr>
{% endfor %}

I end up have this code

{% for row in 'ABCDEFGH' %}
<tr>
  {% for col in '123456789012345' %}
  <td style="text-align: center; border: 1px solid #aaa;">
    {% with forloop.counter|stringformat:"s" as counter %} {% with row|add:counter as seat_num %} {% if seat_num not in oc_seats %}
    <input type="checkbox" value="{{ row }}{{ forloop.counter }}" name="seats"> {% endif %} {{ seat_num }} {% endwith %} {% endwith %}
  </td>
  {% endfor %}
</tr>
{% endfor %}

I tried to disable format on save by changing user settings into {"editor.formatOnSave": false} but still haven't gotten any luck.

Is there any configuration that I can use to make it work better?

PS: I'm using VSCode version 1.9 on Sierra MacOSx


Solution

  • you can disable the default html formatter, goto File > Preferences > User or Workspace Settings, in HTML settings you will find :

    // Enable/disable default HTML formatter (requires restart)
      "html.format.enable": true,
    

    I think VSCode uses js-beautify as default formatter, you can use beautify extension to override it settings with .jsbeautifyrc in project directory