@register.filter(name='highlightpattern') def highlightpattern(string, pattern, points=None, opentag='<b>', closetag='</b>', autoescape=None): """ Highlights the pattern in the text. """ def findall(s, x): start, end = 0, len(s) while start<end: start = s.find(x, start, end) if start != -1: yield start start += len(x) else: start = end def esc(x, n=0): if n!=0: return x if autoescape: return conditional_escape(x) return x if string == None: return '' try: str(pattern) except: print 'Pattern must be a string. Failing silently.' return string try: str(opentag) str(closetag) except: print ('Both `opentag` and `closetag` must be a string. '+ ' Failing silently.') return string if not points: points = list(findall(string, pattern)) l = len(pattern) extra = len(opentag)+len(closetag) o = string for n, i in enumerate(points): o = (esc(o[:i+7*n], n) + opentag + esc(o[i+7*n:i+l+7*n]) + closetag + esc(o[i+l+7*n:])) return mark_safe(o) highlightpattern.needs_autoescape = True highlightpattern.mark_safe = True