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

前端 未结 3 1210
太阳男子
太阳男子 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

提交回复
热议问题