Login

Highlight matched search term

Author:
doniyor
Posted:
May 13, 2014
Language:
Python
Version:
1.4
Tags:
highlighting custom-template-tag
Score:
0 (after 0 ratings)

sterm is the search term. text is the result search text.

it will highlight every matched search term in search result. please define your own .yellow css class.

use:

{{search_result_var|highlight:search_term}}

1
2
3
4
5
6
7
8
9
@register.filter(needs_autoescape=True)
def highlight(text, sterm, autoescape=None):
    if autoescape:
        esc = conditional_escape
    else:
        esc = lambda x: x
    pattern = re.compile('(%s)' % esc(sterm), re.IGNORECASE)
    result = pattern.sub(r'<strong class="yellow">\1</strong>',text)
    return mark_safe(result)

More like this

  1. Tags & filters for rendering search results by exogen 6 years, 11 months ago
  2. highlight text by nathantn 6 months, 2 weeks ago
  3. jQuery ajax search by Peidor 8 years ago
  4. Middleware to detect visitors who arrived from a search engine by exogen 7 years, 10 months ago
  5. Text Highlighting Filter by girasquid 6 years, 2 months ago

Comments

arthur (on May 14, 2014):

You should probably use str.replace(). If you want to use re you should escape input to the filter. If the search term is '.*' it will break, also see https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS

#

doniyor (on May 14, 2014):

thanks Arthur, very good point. i didnot consider this case.

#

Please login first before commenting.