Recently, working with Django, I needed a simple template filter with which highlight a string in a block of text.
I found this snippet (thank you at the author to shared his work) but I modified it because I needed a case insensitive filter. I used it to highlight the filter string in the text resulting of a search.
The filter is really simple but I want post it in order to help someone else who needs something similar.
Here my filter:
from django import template
from django.utils.safestring import mark_safe
register = template.Library()
import re
@register.filter(name='highlight')
def highlight(text, filter):
pattern = re.compile(r"(?P<filter>%s)" % filter, re.IGNORECASE)
return mark_safe(re.sub(pattern, r"<span class='highlight'>\g<filter></span>", text))
To use it in a template you have to define the filter search in this way: {{text_block|highlight:filter_string}}.
After that you need only set the style for the span.highlight in your css file.
Use it








