Reputation: 80415
How can I make the generated HTML be cleaner in terms of whitespce? Django Templating seems to be very sloppy about it. For example, tags it recognizes, like IFs or FORs are parsed then replaced by an empty line. Another example is when I include a file with N linkes of HTML code. If the include statement is tabbed, the first linke from the included file is indented propertly, the rest are pulled to the left.
And so on.
{% spaceless %}
doesn't seem to do anything.
Is there a setting somewhere about how whitespace should be treated? Or another solution?
Thank you.
Upvotes: 2
Views: 1719
Reputation: 45112
There is a ticket in Django's issue tracker about having better handling of whitespace. It was closed as wontfix in 2014, with the following comment:
As far as I know, the consensus among the core team is that:
- the Django template language is good enough for generating HTML, which isn't sensitive to whitespace;
- the long term plan is to replace it with a better engine (most likely Jinja), not to keep working on it;
- if you have more specialized needs (want to generate RTF?) just use another template engine, there are several to choose from.
For HTML output, I'm personally fine with the messy whitespace. It will have minimal effect on HTTP response sizes, if the responses are compressed.
I've had to work on a few cases where precise whitespace and newline control is important (for example, I have a template for Telegram messages, each newline will be a line break in the final message). To tidy up the template, I ended up writing a couple custom tags: {% linemode %}
and {% line %}
.
Example template:
{% linemode %}
{% line %}Line one.{% endline %}
This content will be ignored.
{% if True %}
{% line %}Line two.{% endline %}
{% endif %}
{% endlinemode %}
Result:
Line one.
Line two.
The idea here is that, the {% linemode %}
block will throw away everything that is not also wrapped in {% line %}
tags. That way, the {% if ... %}
and other bits don't add unwanted spaces or newlines. Source here.
Upvotes: 2
Reputation: 686
I found this while looking for the answer to the same question and it seems like there isn't a clean and clear way to do this using the Django syntax (that I have found but I may have overlooked something) so on that note I'd recommend Jinja2. I have experience with using it for whitespace removal with SaltStack. One method is change {% this %}
to {% this -%}
which causes no newline to be appended so if you have a line containing only {% this -%}
then it won't appear as anything in the generated html.
Upvotes: 2
Reputation: 3174
You can override the NodeList's render method as I've done. See my question with working code (applies only to the block and include tags):
Proper indentation in Django templates (without monkey-patching)?
Upvotes: 1