Created
June 4, 2013 10:48
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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