Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to indent Django templates properly

I work in SublimeText 3. When writing Django templates I have a mixture of html and functions.

I like to indent my code so that block, if and other such statements are indented. For example:

Manual formatting

{% extends "accounts/base.html" %}

{% block content %}
  <h1>Password changed</h1>
  <p>Your password was changed.</p>
{% endblock %}

However, when I run any autoformatter HTML-CSS-JS-Prettify it ignores these brackets and treats them as text:

After formatting

{% extends "accounts/base.html" %}
{% block content %}
<h1>Password changed</h1>
<p>Your password was changed.</p>
{% endblock %}

Although plugins like Djaneiro give great tag highlighting, I haven't been able to find a way to get SublimeText to treat these as tags.

Has anyone had any luck?

like image 934
alias51 Avatar asked Aug 30 '19 23:08

alias51


1 Answers

This is a late answer, but I would like to mention a Django template formatter that I've created myself: DjHTML. You can install it using pip install djhtml.

Let's say template.html contains the following:

{% extends "accounts/base.html" %}
{% block content %}
<h1>Password changed</h1>
<p>Your password was changed.</p>
<script>
$(function() {
console.log("Password changed!");
});
</script>
{% endblock %}

Then running djhtml template.html will give the following output:

{% extends "accounts/base.html" %}
{% block content %}
    <h1>Password changed</h1>
    <p>Your password was changed.</p>
    <script>
        $(function() {
            console.log("Password changed!");
        });
    </script>
{% endblock %}

It's easiest to use DjHTML as a pre-commit hook, so that templates will be automatically indented when you run git commit. Instructions on how to configure pre-commit can be found in the README.

like image 140
Jaap Joris Vens Avatar answered Sep 19 '22 11:09

Jaap Joris Vens