Django template indentation guideline
django, indentation, templates
Solution
I am currently following my own convention in django template guideline for consistency matter. The rule is simple:
- Django tag does NOT increase the indentation level
- HTML tag does increase the indentation level
It does not matter how many nested Django Tag you have, you should still on the same level of indentation. I consider this as the trade off for putting logic in templates which should be minimized if possible to avoid confusion.
<html>
<body>
<ul>
{% if condition %}
{% for item in menu_item %}
<li>{{ item }}</li>
{% endfor %}
{% endif %}
</ul>
<main>
{% block content %}
<p>Hello World</p>
{% endblock content %}
</main>
</body>
</html>
Side note
I am using 2 spaces for HTML indentation, because HTML tends to have a very deep nested.
For Vim user, please note that the syntax is not `html` but `htmldjango`
Thus my `~/.vimrc` looks something like:
autocmd Filetype htmldjango setlocal ts=2 sts=2 sw=2 expandtab
Problem
There is PEP 8 for Python, but I haven't seen a preferred indentation guideline for django templates. What I mean is, I normally indent blocks like this: ``` <span>outside</span> {% if condition %} <span>within condition</span> {% endif %} <span>outside</span> ``` While this looks good on the editor, but it will look crap on view source like this: ``` <span>outside</span> <span>within condition</span> <span>outside</span> ``` It would even look worse within the HTML indentation, see below: ``` <div> <span>outside</span> {% if condition %} <span>within condition</span> {% endif %} </div> ``` will become: ``` <div> <span>outside</span> <span>within condition</span> </div> ``` While I agree having better layout in editor is way way more important, but I also get paranoid about the generated messy HTML source code.