How to highlight searched queries in result page of Django template?

前端 未结 3 1196
太阳男子
太阳男子 2021-01-03 11:44

I have the following search query in views.py:

class SearchView(View):
    def get(self, request, *args, **kwargs):
        queryset = BlogPost.         


        
相关标签:
3条回答
  • 2021-01-03 11:58

    You can also use a function from django-haystack but you will need to configure the simple backend on your settings:

    pipenv install django-haystack

    Your settings.py

    INSTALLED_APPS = (
       'haystack'
    )
    
    HAYSTACK_CONNECTIONS = {
        'default': {
            'ENGINE': 'haystack.backends.simple_backend.SimpleEngine',
        },
    }
    

    Create a new template filter:

    @register.filter
    def highlight_search(text, search):
        from haystack.utils.highlighting import Highlighter
        highlight = Highlighter(search, html_tag='strong', css_class='highlighted', max_length=400)
    
        return highlight.highlight(text)
    

    Your template will look something like this:

    {{ result.htmldata|highlight_search:myquery|safe  }}
    

    The built-in safe will render the html_tag that you choose on your implementation.

    More info: https://django-haystack.readthedocs.io/en/master/highlighting.html

    0 讨论(0)
  • 2021-01-03 11:58

    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 %}
    

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

    0 讨论(0)
  • 2021-01-03 12:12

    Try changing backgroud-color for the div in which search results are being appended like

    .link {
        background-color: yellow;
    }
    
    0 讨论(0)
提交回复
热议问题