Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django template indentation guideline

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.

like image 846
James Lin Avatar asked Aug 27 '13 03:08

James Lin


2 Answers

I am currently following my own convention in django template guideline for consistency matter. The rule is simple:

  1. Django tag does NOT increase the indentation level
  2. 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
like image 168
Yeo Avatar answered Oct 28 '22 11:10

Yeo


Depending your editor, there are ways to set a specific indent width for HTML files.

As for the Django tags, it is actually a good thing not to not add a indent level. See that example:

<ul>
    {% for item in items %}
        <li>{{ item }}</li>
    {% endfor %}
</ul>

Would be rendered like so:

<ul>
        <li>Bacon</li>
        <li>Ninja</li>
        <li>Tumbleweed</li>
</ul>

And we do not want the two levels of indent. Instead:

{% block content %}
<ul>
    {% for item in items %}
    <li>{{ item }}</li>
    {% endfor %}
</ul>
{% endblock content %}
like image 35
Mathieu Marques Avatar answered Oct 28 '22 11:10

Mathieu Marques