import re
from django import template
from django.utils.encoding import force_unicode
from django.utils.functional import allow_lazy

register = template.Library()

def skip_spaces(value):
    "Return the given HTML with specified spaces removed."
    return re.sub(r'\s*&nosp;', '', force_unicode(value)) # Remove all whitespace before &nosp; along with &nosp; itself
skip_spaces = allow_lazy(skip_spaces, unicode)

class SkipSpacesNode(template.Node):
    def __init__(self, nodelist):
        self.nodelist = nodelist

    def render(self, context):
        return skip_spaces(self.nodelist.render(context).strip())

@register.tag
def skipspaces(parser, token):
    """like spaceless, but removes spaces only where specified by &nosp; entities"""
    nodelist = parser.parse(('endskipspaces',))
    parser.delete_first_token()
    return SkipSpacesNode(nodelist)
