[Django]-Highlighting searched text in django

6👍

You can make use of a regular expression here:

from re import IGNORECASE, compile, escape as rescape

register = template.Library()

@register.filter(name='highlight')
def highlight(text, search):
    rgx = compile(rescape(search), IGNORECASE)
    return mark_safe(
        rgx.sub(
            lambda m: '<b class="text text-danger">{}</b>'.format(m.group()),
            text
        )
    )

Leave a comment