[Fixed]-Creating readable html with django templates


Christian S. Perone from Pyevolve has exactly what you’re looking for. He uses middleware to intercept the HTTPResponse object and run it through BeautifulSoup.

I’d imagine that your site will suffer a slight performance hit, though. I recommend running some benchmarks before deploying this middleware to a production site.



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)?


I’m impressed you care about the resulting html – I only worry about getting the templates tidy and readable! But in answer to your question, have you looked at middleware?


Then use the Tidy python module to reformat the html.



I recommend to run the output of the template engine through an HTML tidier, such as µTidylib.


The readability of HTML doesn’t matter. In a system like Django or Rails, HTML is an output format, not a source format. When people edit HTML by hand, they are right to be concerned about indentation and spacing, because it is a source format, and someone will have to edit it in the future. But the output of templates is just that: output. The browser doesn’t care about the indentation. At this point the only people who read the HTML are people looking at View – Source.


If you’re using Django Templates to do string-formatting of long-but-simple strings, you can use Python’s triple-quoted strings with .format() in a function def:

def templated_string(context_dict):
    return '''This is an example
of a long string across multiple lines.
It can be used to format {something} for 
{name}'s own purposes, even though
it looks funny in code'''.format(**context_dict)

Then templated_string({'name': 'rileymat', 'something': 'whatever you want'}) does the sensible thing. You can generate raw HTML that way… which then has exactly the whitespace you ask for.

Leave a comment