I am currently working on a unique template filter that will enhance search results by highlighting keywords, similar to how Google search results are displayed.
Here is the code for the custom filter:
register = template.Library()
@register.filter
@stringfilter
def highlight(value, search_term):
return value.replace(search_term, "<span class='highlight'>%s</span>" % search_term)
However, the filter currently does not apply the CSS class <span class='highlight'>
to the targeted word. Instead, it displays the text in the browser exactly as
<span class='highlight'>word</span>
. For example, "The most desired car brand right now is <span class='highlight'>Tesla</span>
." How can I modify the code to actually change the CSS class of the targeted word using the replace()
method?