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 %}
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:
- Pagination and get parameters
- Best way of linking to a page in Django
- Add confirmation step to custom Django management/manage.py command
- How to use Django variable in JavaScript file?
- Easy Way to Escape Django Template Variables
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)?
- Printing Django QuerySet SQL with ""
- Resize image on save
- Django Bi-directional ManyToMany – How to prevent table creation on second model?
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.