Last active
January 1, 2016 20:19
-
-
Save minddust/8196664 to your computer and use it in GitHub Desktop.
Django spaceless with preserved pre formatting
This file contains 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
"""Copyright (c) 2013-2014 Stephan Groß, under MIT license.""" | |
from __future__ import unicode_literals | |
import re | |
from django import template | |
from django.template import Node | |
from django.utils import six | |
from django.utils.encoding import force_text | |
from django.utils.functional import allow_lazy | |
register = template.Library() | |
def strip_spaces_between_tags_except_pre(value): | |
def replacement(count, matches, match): | |
matches.append(match.group(0)[1:-1]) # save the whole match without leading "<" and trailing ">" | |
count[0] += 1 | |
return '<{{{0}}}>'.format(count[0]) # add "<" and ">" to preserve space stripping | |
count = [-1] | |
matches = [] | |
value = re.sub(r'<pre(\s.*)?>(.*?)</pre>', lambda match: replacement(count, matches, match), force_text(value), flags=re.S | re.M | re.I) | |
value = re.sub(r'>\s+<', '><', force_text(value)) | |
return value.format(*matches) | |
strip_spaces_between_tags_except_pre = allow_lazy(strip_spaces_between_tags_except_pre, six.text_type) | |
class SpacelessExceptPreNode(Node): | |
def __init__(self, nodelist): | |
self.nodelist = nodelist | |
def render(self, context): | |
return strip_spaces_between_tags_except_pre(self.nodelist.render(context).strip()) | |
@register.tag | |
def spaceless_except_pre(parser, token): | |
"""Remove whitespace between HTML tags, including tab and newline characters except content between <pre>""" | |
nodelist = parser.parse(('endspaceless_except_pre',)) | |
parser.delete_first_token() | |
return SpacelessExceptPreNode(nodelist) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
reddit comments:
http://www.reddit.com/r/django/comments/1u38mu/django_spaceless_with_preserved_pre_formatting/