Created
March 27, 2012 21:38
-
-
Save un33k/2220576 to your computer and use it in GitHub Desktop.
high light search result
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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