Search code examples
pythonhtmldjangowebstormcode-formatting

Is it possible to set up auto indent for Django/html templates in WebStorm?


Problem: When I auto intent it removes all indentation any markup/python logic in the template.

Is there a plugin to afford auto indent for Django templates? If not, how can I edit the Auto-indent Lines command ⌃⌥I to support formatting described below:

index.html:

{% block title %}
  {# note the indent here with django logic #}
  {% render title_tag with title="Sign up Now" global=global %}
{% endblock %}

{% block description %}
  {# note the indent here with html markup #}
  <meta name="description" content="Sign up today with our product.">
{% endblock %}

{% block body %}
{# note the indent here If statement #}
{% if true %}
  <section class="section">
    <p> here too</p> 
  </section>
  {% if false %}
    <div>
      <p>wowo</p>
    </div>
   {% endif %}
{% endif %}

Solution

  • Answer:

    In order to format such stuff more-or-less properly (e.g. keep indentation inside blocks) IDE must understand Django tags. WEB-7814 ticket is asking just about that (star/vote/comment to get notified on any progress).

    Right now I may only suggest to try to install "Twig Support" plugin (should work with WebStorm). Twig uses very similar syntax (inspired by Django) so it should help here. Otherwise -- PyCharm or full IntelliJ with Python plugin.



    Twig plugin: Installation Guide for Plugins + Formatting + Usage

    • Open: Main menu > Webstorm > Preferences
    • Search for "Plugin"

    Step 1 Step 2 Step 3

    • Install Twig Support.
    • Restart Webstorm.
    • Open: Main menu > Webstorm > Preferences.
    • Search "Twig"
    • Go to Editor > Code Style > Twig Step 4
    • Set tab size and indentation to 2.
    • Press apply.
    • Search for "File Types"
    • Click on "Editor > File Types" Step 5
    • Go to "Twig inside of "Recognized File Types" Pane. Step 6
    • Click the "+" and add ".html" ".tpl" Note: You may get an error saying this file extensions are already used else where. Override the previous use.

    Step 7

    • Click Apply.
    • Restart Webstorm.

    Auto indent