sterm is the search term. text is the result search text.
it will highlight every matched search term in search result. please define your own .yellow css class.
use:
{{search_result_var|highlight:search_term}}
1 2 3 4 5 6 7 8 9 | @register.filter(needs_autoescape=True)
def highlight(text, sterm, autoescape=None):
if autoescape:
esc = conditional_escape
else:
esc = lambda x: x
pattern = re.compile('(%s)' % esc(sterm), re.IGNORECASE)
result = pattern.sub(r'<strong class="yellow">\1</strong>',text)
return mark_safe(result)
|
More like this
- New Snippet! by Antoliny0919 4 days, 16 hours ago
- Add Toggle Switch Widget to Django Forms by OgliariNatan 2 months, 3 weeks ago
- get_object_or_none by azwdevops 6 months, 2 weeks ago
- Mask sensitive data from logger by agusmakmun 8 months, 1 week ago
- Template tag - list punctuation for a list of items by shapiromatron 1 year, 10 months ago
Comments
You should probably use
str.replace(). If you want to usereyou should escape input to the filter. If the search term is '.*' it will break, also see https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS#
thanks Arthur, very good point. i didnot consider this case.
#
Please login first before commenting.