I'm having a hard time trying to get Django's template engine to indent properly when extending/including templates
these files :
index.html
<html>
<body>
<div id="hello">
{% block bar %}
{% endblock %}
{% include 'baz.html'%}
</div>
</body>
</html>
bar.html
{% extends 'foo.html' %}
{% block bar %}
<p>bar</p>
{% endblock %}
baz.html
<p>baz</p>
will render as
<html>
<body>
<div id="hello">
<p>bar</p>
<p>baz</p>
</div>
</body>
</html>
How can I fix it so it renders as
<html>
<body>
<div id="hello">
<p>bar</p>
<p>baz</p>
</div>
</body>
</html>
Manually entering tabs is not an option. I am using soft tabs (4 spaces) if ever this matters.
{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.
A for loop is used for iterating over a sequence, like looping over items in an array, a list, or a dictionary.
Django Template Engine provides filters which are used to transform the values of variables;es and tag arguments. We have already discussed major Django Template Tags. Tags can't modify value of a variable whereas filters can be used for incrementing value of a variable or modifying it to one's own need.
This flag tells Django that if a “safe” string is passed into your filter, the result will still be “safe” and if a non-safe string is passed in, Django will automatically escape it, if necessary. You can think of this as meaning “this filter is safe – it doesn't introduce any possibility of unsafe HTML.”
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 %}
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With