[Fixed]-Creating readable html with django templates

16👍

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.

👤Shane

4👍

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

0👍

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?

http://docs.djangoproject.com/en/dev/topics/http/middleware/

Then use the Tidy python module to reformat the html.

http://pypi.python.org/pypi/PythonTidy/

0👍

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

0👍

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.

0👍

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