通过replace()将高亮效果应用于文本(Django 2.1) [英] Applying highlighting effect to text through replace() (Django 2.1)

查看:67
本文介绍了通过replace()将高亮效果应用于文本(Django 2.1)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个自定义模板过滤器,以突出显示在搜索结果页面中放入搜索引擎的关键字,就像在Google搜索结果中一样.

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.

自定义过滤器的代码:

register = template.Library()
@register.filter
@stringfilter
def highlight(value, search_term):
    return value.replace(search_term, "<span class='highlight'>%s</span>" % search_term)

过滤器不会将目标单词的CSS类更改为< span class ='highlight'> .而是在浏览器中输出的显示文字实际上是< span class ='highlight'> word</span> .例如.目前最需要的汽车品牌是< span class ='highlight'> Tesla</span> ."如何才能使 replace()方法实际上更改目标单词的CSS类?

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?

推荐答案

问题是,当您过滤对HTML元素进行的更改时,您需要自动换景

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

工作代码:

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))

这篇关于通过replace()将高亮效果应用于文本(Django 2.1)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆