Этот тег шаблона будет выделять слова только для текстовой части HTML-кода.
import re
from django import template
from django.utils.safestring import mark_safe
register = template.Library()
@register.tag(name="highlight")
def do_highlight(parser, token):
tag_name, words = token.contents.split(' ', 1)
nodelist = parser.parse(('endhighlight',))
parser.delete_first_token()
return HighlightNode(nodelist, words)
class HighlightNode(template.Node):
def __init__(self, nodelist, words):
self.nodelist = nodelist
self.words = words
def render(self, context):
# initial data
html_data = self.nodelist.render(context)
# prepare words to be highlighted
words = context.get(self.words, "")
if words:
words = [w for w in re.split('[^\w]+', words) if w]
pattern = re.compile(r"(?P<filter>%s)" % '|'.join(words), re.IGNORECASE)
else :
# no need to go further if there is nothing to highlight
return html_data
# parse the html
chunks = html_data.split('<')
parsed_data = [chunks.pop(0)]
# separate tag and text
for chunk in chunks:
if chunk:
if '>' in chunk:
tagdata, text = chunk.split('>', 1)
endtag = '>'
else:
# the tag didn't end
tagdata, text, endtag = chunk, '', ''
# rebuild tag
parsed_data.append('<')
parsed_data.append(tagdata)
parsed_data.append(endtag)
# highligh words in text
if text:
text = mark_safe(re.sub(pattern,
r'<span class="highlight">\g<filter></span>',
text))
parsed_data.append(text)
return ''.join(parsed_data)