Skip to content

Instantly share code, notes, and snippets.

@simonw
Created June 4, 2013 10:48
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 simonw/5705089 to your computer and use it in GitHub Desktop.
Save simonw/5705089 to your computer and use it in GitHub Desktop.
Because sometimes the fact that template tag indentation screws up the indentation in view source really bugs me. No, we don't run this in production.
import re
leading_tab_re = re.compile('^(\t+)')
class ReindentingMiddleware(object):
def process_response(self, request, response):
return response
if not response['Content-Type'].startswith('text/html'):
return response
content = response.content
lines = content.split('\n')
fixed_lines = []
current_indent = 0
for line in lines:
if not line.strip():
continue
m = leading_tab_re.match(line)
if m is not None:
num_tabs = len(m.group(1))
if num_tabs > current_indent:
current_indent += 1
elif num_tabs < current_indent:
current_indent -= 1
line = leading_tab_re.sub('\t' * current_indent, line)
fixed_lines.append(line)
response.content = '\n'.join(fixed_lines)
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment