问题
I am writing a custom template filter that highlights the keyword put into the search engine in the search results page, just like in Google search results.
Code for 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)
The filter doesn't change the targeted word's CSS class into <span class='highlight'>
. Instead, the output displayed text in the browser is literally <span class='highlight'>word</span>
. E.g. "The most desired car brand right now is <span class='highlight'>Tesla</span>
." How can I make it so that the replace()
method actually changes the CSS class of the targeted word?
回答1:
The issue is that you need to autoscape when you filter makes changes to HTML elements https://docs.djangoproject.com/en/2.1/howto/custom-template-tags/#filters-and-auto-escaping
Working code:
from django import template
from django.utils.safestring import mark_safe
from django.utils.html import conditional_escape
from django.template.defaultfilters import stringfilter
register = template.Library()
@register.filter(needs_autoescape=True)
@stringfilter
def highlight(value, search_term, autoescape=True):
return mark_safe(value.replace(search_term, "<span class='highlight'>%s</span>" % search_term))
来源:https://stackoverflow.com/questions/54393614/applying-highlighting-effect-to-text-through-replace-django-2-1