如何在Django模板的结果页面中突出显示搜索到的查询? [英] How to highlight searched queries in result page of Django template?

查看:241
本文介绍了如何在Django模板的结果页面中突出显示搜索到的查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 views.py 中有以下搜索查询:

I have the following search query in views.py:

class SearchView(View):
    def get(self, request, *args, **kwargs):
        queryset = BlogPost.objects.all()
        query = request.GET.get('q')
        if query:
            queryset = queryset.filter(
                Q(title__icontains=query) |
                Q(content__icontains=query)
            ).distinct()
        context = {
            'queryset': queryset,
            'query': query,
        }
        return render(request, 'blogs/search_result.html', context)

,如果我搜索的是 Tesla 结果模板中显示的结果如下:

and if I search a word like Tesla the results shown in result template is as below:

请帮助我,如何突出显示s在Django模板中获取黄色查询?谢谢您的帮助!

Please help me, how do I highlight the searched query in yellow color in Django templates? Thank you for help!

编辑:
这是带有搜索框的模板代码

edit: This is the template code with search box

<div class="card my-4">
    <div class="card-body">
        <div class="card-title">Search blog</div>
        <form action="{% url 'blog:search_blog' %}">
            {% csrf_token %}
            <input type="text" class="form-control" name="q" placeholder="What are you looking for?">
            <input type="submit" value="Search" class="btn btn-success btn-sm mt-3">
        </form>
    </div>
</div>

这是result_search的模板

This is the template for result_search

{% block content %}
<div class="container bg-light w-100">
    <h2 class="display-6 border-bottom py-3">Results for "{{ query }}"</h2>
    {% for post in queryset %}
    <div class="my-1">
        <a class="link" href="{{ post.get_absolute_url }}">{{ post.title }}</a>
    </div>
    {% endfor %}
</div>
{% endblock %}

谢谢

编辑2:Daniel Roseman,先生,这是下面的html,我用黄色突出显示了它。

Edit 2: Daniel Roseman, Sir this is the html below I highlighted it in yellow.

推荐答案

您可以在模板过滤器中执行此操作。像这样的东西:

You could do this in a template filter. Something like:

@register.filter
def highlight_search(text, search):
    highlighted = text.replace(search, '<span class="highlight">{}</span>'.format(search)
    return mark_safe(highlighted)

现在您可以在模板中执行以下操作:

Now in your template you can do:

{% load my_tags %} # wherever you put the template filter

{% for post in queryset %}
<div class="my-1">
    <a class="link" href="{{ post.get_absolute_url }}">{{ post.title|highlight_search:query }}</a>
</div>
{% endfor %}

您需要将search_text与呈现结果页面的上下文一起发送回去。

You'd need to send the search_text back with the context that renders the result page.

这篇关于如何在Django模板的结果页面中突出显示搜索到的查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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