[Fixed]-Django template engine indentation

7đź‘Ť

âś…

Indentation is not automatically inserted by Django template inheritence. To achieve the indentation you desire you’d need to include it within bar.html:

{% extends 'foo.html' %}

{% block bar %}
            <p>bar</p>
{% endblock %}
👤bradley.ayers

4đź‘Ť

You should explain with is the purpose of your indentation needs.

Indentation is very useful in debug step, but indentation is not compatible with optimization, because this exists spaceless filter.

You can write your own snipped:

@register.tag
def myinden(parser, token):
    args = token.contents.split()
    n = args[1]
    nodelist = parser.parse(('endmyinden',))
    parser.delete_first_token()
    return MyIndenNode(nodelist, n)

class MyIndenNode(Node, n):
    def __init__(self, nodelist, n):
        self.nodelist = nodelist
        self.n = n

    def render(self, context):
        import re
        regex = re.compile("^", re.M)
        return re.sub(regex, "\t"*int(self.n),
                      self.nodelist.render(context).strip())

To usage:

index.html
{% include 'baz.html' with indentation="8" %}

baz.html
{{ myindent:myindentation }}
...

Notice, not tested. Also, I suggest to you to modify snippet to works only in debug mode:

👤dani herrera

1đź‘Ť

You can override the NodeList’s render method as I’ve done. See my question with working code:

Proper indentation in Django templates (without monkey-patching)?

👤HankMoody

1đź‘Ť

Another option from the above mentioned is to use Beautiful Soup middleware.

Here is a tutorial. Note, that people call this middleware to be “REALLY SLOW” and advice caching the output pages.

Leave a comment