Flask结合SQLAlchemy如何实现搜索关键词在结果页高亮显示
搜索关键词高亮实现方案
步骤1:添加自定义高亮过滤器并修改路由
首先在你的Flask启动文件中新增Jinja2自定义过滤器,用于安全替换匹配的关键词,同时修改路由将搜索词传递到模板:
from flask import Flask, request, render_template from jinja2 import Markup import re # 你原有其他初始化代码、数据库模型定义保持不变 # 自定义关键词高亮过滤器 def highlight_keyword(text, keyword): if not keyword or not text: return Markup.escape(text) # 转义内容避免XSS风险,转义关键词避免正则解析错误 escaped_text = Markup.escape(text) escaped_keyword = re.escape(keyword) # 忽略大小写匹配关键词,用原生高亮标签包裹 highlighted = re.sub( f'({escaped_keyword})', r'<mark>\1</mark>', escaped_text, flags=re.IGNORECASE ) return Markup(highlighted) # 注册过滤器到Flask应用 app.add_template_filter(highlight_keyword) @app.route("/post") def post(): term = request.args.get("search_text", None) if term == None: scanned = Images.query.filter_by().all()[0:15] # 非搜索场景传空关键词避免模板报错 return render_template('post.html', scanned=scanned, search_term='') else: search = "%{}%".format(term) scanned = Images.query.filter(or_(Images.content.like(search),Images.title.like(search))) # 搜索场景传递搜索关键词到模板 return render_template('post.html', scanned=scanned, search_term=term)
步骤2:添加高亮样式
在post.html的<head>标签内添加高亮样式,你可以根据需求自定义样式效果:
<style> mark { background-color: #fff350; padding: 0 3px; border-radius: 2px; font-weight: 500; } </style>
步骤3:修改模板渲染逻辑
将原有模板中直接输出标题、内容的部分,替换为调用高亮过滤器的写法:
{% for scanned in scanned %} <div class="post-preview"> <a href="/post2/{{scanned.Slug}}"> <h2 class="post-title">{{ scanned.title|highlight_keyword(search_term) }}</h2> </a> <p class="Images-meta">Posted by <a href="#">Admin</a> on {{scanned.Date}}</p> </div> {{scanned.content[0:120]|highlight_keyword(search_term)}}... <hr> {% endfor %}
以上实现默认支持大小写不敏感的关键词高亮,如果你需要严格匹配大小写,删除过滤器中flags=re.IGNORECASE参数即可。
内容的提问来源于stack exchange,提问作者Muhammad Bilal
相关产品推荐
相关产品推荐

