I have the following search query in views.py
:
class SearchView(View):
def get(self, request, *args, **kwargs):
queryset = BlogPost.
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
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.
Try changing backgroud-color
for the div
in which search results are being appended like
.link {
background-color: yellow;
}