Skip to content

Instantly share code, notes, and snippets.

@un33k
Created March 27, 2012 21:38
Show Gist options
  • Select an option

  • Save un33k/2220576 to your computer and use it in GitHub Desktop.

Select an option

Save un33k/2220576 to your computer and use it in GitHub Desktop.
high light search result
import re
from django import template
from django.template import Node, TemplateSyntaxError
from django.conf import settings
from django.utils.safestring import mark_safe
from wwwsite.applications.portal.utils.search import get_tokenize
register = template.Library()
def highlight_word(needles, haystack, class_name='highlight'):
regex = re.compile(r"(%s)" % "|".join(needles), re.I)
i = 0; highlighted = ""
for m in regex.finditer(haystack):
highlighted += "".join([haystack[i:m.start()], "<strong>",haystack[m.start():m.end()], "</strong>"])
i = m.end()
highlighted += haystack[i:]
highlighted = mark_safe(highlighted)
return highlighted
@register.filter
def highlight(keywords, string):
"""
given an list of words, this tag highlights the match words in the given string
"""
if not keywords:
return string
include, exclude = get_tokenize(keywords)
highlighted = highlight_word(include, string)
return highlighted
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment