This is an enhancement of snippet #172. Here I use BeautifulSoup — far more easier to install through pip in a virtualenv, and possibly a bit more maintained — to format and properly indent the rendered HTML from templates.
I also added a check to only tidy contents in a DEBUG=True environment, regarding high impact on performance while doing so in production.
Last, it's compatible with Django 1.2.x.
1 2 3 4 5 6 7 8 9 10 11 | import settings
from BeautifulSoup import BeautifulSoup
class PrettifyMiddleware(object):
"""HTML code prettification middleware."""
def process_response(self, request, response):
if settings.DEBUG and response['Content-Type'].split(';', 1)[0] == 'text/html':
response.content = BeautifulSoup(response.content).prettify()
return response
|
More like this
- New Snippet! by Antoliny0919 4 days, 19 hours ago
- Add Toggle Switch Widget to Django Forms by OgliariNatan 2 months, 3 weeks ago
- get_object_or_none by azwdevops 6 months, 2 weeks ago
- Mask sensitive data from logger by agusmakmun 8 months, 1 week ago
- Template tag - list punctuation for a list of items by shapiromatron 1 year, 10 months ago
Comments
It's ok n1k0. Yours version of PrettifyMiddleware is better because #570 don't check DEBUG status.
#
Please login first before commenting.