Skip to content

Instantly share code, notes, and snippets.

@seddonym
Created August 19, 2015 09:09
Show Gist options
  • Save seddonym/7f4a6bcd67d711ceb2fd to your computer and use it in GitHub Desktop.
Save seddonym/7f4a6bcd67d711ceb2fd to your computer and use it in GitHub Desktop.
How to override faulty behaviour of Haystack highlighting
import re
from haystack.utils.highlighting import Highlighter as FaultyHighlighter
class Highlighter(FaultyHighlighter):
"""Highlighter that fixes the issue with highlighting parts of words:
https://github.com/django-haystack/django-haystack/issues/378
"""
def find_highlightable_words(self):
word_positions = {}
lower_text_block = self.text_block.lower()
for word in self.query_words:
# Use a regular expression to search by whole words
# \b corresponds to a word boundary
matches = re.finditer(r'\b%s\b' % word, lower_text_block)
if matches:
word_positions[word] = [match.start() for match in matches]
return word_positions
HAYSTACK_CUSTOM_HIGHLIGHTER = 'myapp.highlighting.Highlighter'
@robslotboom
Copy link

Thanks for this sollution.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment