Skip to content

Instantly share code, notes, and snippets.

@etianen
Created March 15, 2014 16:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save etianen/9569715 to your computer and use it in GitHub Desktop.
Save etianen/9569715 to your computer and use it in GitHub Desktop.
@register.filter
def search_description(obj, query):
for term in [query] + query.split():
pattern = re.compile(re.escape(term), re.IGNORECASE)
if pattern.search(obj.title):
return obj.description
for content in (obj.description, obj.content):
match = pattern.search(content)
if match:
start = max(match.start() - 100, 0)
while start > 0 and content[start] not in (" ", "\t", "\n", "\r"):
start -= 1
end = min(match.end() + 100, len(content))
while end < len(content) and content[end] not in (" ", "\t", "\n", "\r"):
end += 1
content_sub = content[start:end]
def replace_match(match):
return u"<strong>{match}</strong>".format(
match = match.group(),
)
content_sub = pattern.sub(replace_match, content_sub)
if start > 0:
content_sub = u"…" + content_sub
if end < len(content):
content_sub += u" …"
return content_sub
return obj.description
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment