Login

Analogue template filter to removetags that also removes the content of the tag

Author:
piquadrat
Posted:
November 12, 2010
Language:
Python
Version:
Not specified
Score:
1 (after 1 ratings)

Django's builtin removetags filter removes the supplied tags, but leaves the enclosed text alone. Sometimes you need the complete tag, including its content to go away. Example:

<h1>Some headline</h1>
<p>Some text</p>

Applying removetags:"h1" to this html results in

Some headline
<p>Some text</p>

while killtags:"h1" leaves

<p>Some text</p>
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import re
from django.template.defaultfilters import stringfilter
from django.template import Library

register = Library()

@register.filter
@stringfilter
def killtags(value, tags):
    tags = [re.escape(tag) for tag in tags.split()]
    tags_re = u'(%s)' % u'|'.join(tags)    
    kill_re = re.compile("<\s*%s[^>]*>(.*?)<\s*/\s*\\1>" % tags_re, re.U)
    value = kill_re.sub('', value)
    return value
killtags.is_safe = True

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.