Skip to content

Instantly share code, notes, and snippets.

@DWboutin
Created August 23, 2018 14:48
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
Django filter to keep only wanted HTML tags
from django import template
from django.utils.html import format_html
from django.template.defaultfilters import stringfilter
register = template.Library()
@register.filter(name='keeptags')
@stringfilter
def keeptags(value, tags):
"""
Strips all [X]HTML tags except the space seperated list of tags
from the output.
Usage: keeptags:"strong em ul li"
"""
import re
from django.utils.html import strip_tags, escape
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 format_html(value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment