Login

Text Highlighting Filter

Author:
girasquid
Posted:
December 10, 2008
Language:
Python
Version:
1.0
Score:
0 (after 0 ratings)

This filter can be used to wrap <span class='highlight'> around anything you want to highlight in a block of text. For example, if you had 'foo bar foo baz' inside the context variable MYTEXT, you could do {{ MYTEXT|highlight:'foo' }}, and "<span class='highlight'>foo</span> bar <span class='highlight'>foo</span> baz" would be returned.

How you style the highlight class is up to you.

1
2
3
@register.filter
def highlight(text, word):
    return mark_safe(text.replace(word, "<span class='highlight'>%s</span>" % word))

More like this

  1. LazyPrimaryKeyRelatedField by LLyaudet 2 days, 18 hours ago
  2. CacheInDictManager by LLyaudet 3 days, 1 hour ago
  3. MYSQL Full Text Expression by Bidaya0 3 days, 19 hours ago
  4. Custom model manager chaining (Python 3 re-write) by Spotted1270 1 week, 3 days ago
  5. Django Standard API Response Middleware for DRF for modern frontend easy usage by Denactive 3 weeks, 4 days ago

Comments

Ana_Pana (on February 27, 2014):

Great solution! Thank you!

#

Please login first before commenting.