Login

Text Highlighting Filter

Author:
girasquid
Posted:
December 10, 2008
Language:
Python
Version:
1.0
Tags:
filter text highlight
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. Humanize lists of strings in templates by ChipX86 8 years, 1 month ago
  2. Readonly fields on Form/Modelform by Killarny 6 years, 5 months ago
  3. Get derived model instance by werehuman 1 year, 10 months ago
  4. {% ifthis FOO isoneof BAR BAZ ... %} by sjl 5 years, 2 months ago
  5. Tags & filters for rendering search results by exogen 7 years, 4 months ago

Comments

Ana_Pana (on February 27, 2014):

Great solution! Thank you!

#

Please login first before commenting.