Applying highlighting effect to text through replace() (Django 2.1)

余生长醉 提交于 2021-02-11 13:55:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!