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
Tags:
filter removetags
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. render_markup filter, specify the markup filter as a string by exogen 8 years ago
  2. filter for extracting a number of paragraphs from any HTML code by rafadev 3 years, 11 months ago
  3. YUI Loader as Django middleware by akaihola 7 years ago
  4. Django filter stack to cleanup WYSIWYG output by jbergantine 3 years, 8 months ago
  5. Template tag to sort a list of links by pytechd 7 years, 8 months ago

Comments

Please login first before commenting.