Skip to content

Instantly share code, notes, and snippets.

@maximegaillard
Created September 14, 2011 14:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maximegaillard/1216644 to your computer and use it in GitHub Desktop.
Save maximegaillard/1216644 to your computer and use it in GitHub Desktop.
Django Middleware Compress HTML
import re
from django.utils.html import strip_spaces_between_tags
from django.conf import settings
RE_MULTISPACE = re.compile(r"\s{2,}")
RE_NEWLINE = re.compile(r"\n")
class MinifyHTMLMiddleware(object):
def process_response(self, request, response):
if 'text/html' in response['Content-Type'] and settings.COMPRESS_HTML:
response.content = strip_spaces_between_tags(response.content.strip())
response.content = RE_MULTISPACE.sub(" ", response.content)
response.content = RE_NEWLINE.sub("", response.content)
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment