- Author:
- nicolaslara
- Posted:
- April 19, 2009
- Language:
- Python
- Version:
- 1.0
- Score:
- 0 (after 0 ratings)
Encloses all matches of a pattern between the opentag and closetag string.
{% with "this is a large test" as a %}
{{ a|highlightpattern:"a" }}
{% endwith %}
yields
this is <b>a</b> l<b>a</b>rge test
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
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Please login first before commenting.