highlight pattern

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
@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

More like this

  1. Pagination/Filtering Alphabetically by zain 4 years, 2 months ago
  2. Parsing and Highlighting &lt;code&gt; Blocks by joshua 6 years, 2 months ago
  3. Text Highlighting Filter by girasquid 4 years, 5 months ago
  4. Breadcrumbs filter by Oggu 4 years, 4 months ago
  5. Tags & filters for rendering search results by exogen 5 years, 2 months ago

Comments

(Forgotten your password?)