Skip to content

Instantly share code, notes, and snippets.

@xfenix
Last active December 12, 2015 10:39
Show Gist options
  • Save xfenix/4761121 to your computer and use it in GitHub Desktop.
Save xfenix/4761121 to your computer and use it in GitHub Desktop.
from django.utils.html import strip_tags, escape
from django.utils.safestring import mark_safe
"""
Strips all [X]HTML tags except the space seperated list of tags
from the output.
Usage: keeptags:"strong em ul li"
"""
def keep_tags(value, tags):
tags = [re.escape(tag) for tag in tags.split()]
tags_re = '(%s)' % '|'.join(tags)
singletag_re = re.compile(r'<(%s\s*/?)>' % tags_re)
starttag_re = re.compile(r'<(%s)(\s+[^>]+)>' % tags_re)
endtag_re = re.compile(r'<(/%s)>' % tags_re)
value = singletag_re.sub('##~~~\g<1>~~~##', value)
value = starttag_re.sub('##~~~\g<1>\g<3>~~~##', value)
value = endtag_re.sub('##~~~\g<1>~~~##', value)
value = strip_tags(value)
value = escape(value)
recreate_re = re.compile('##~~~([^~]+)~~~##')
value = recreate_re.sub('<\g<1>>', value)
return html_entity_decode(value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment