Fel
Fel

Reputation: 61

How do I highlight a particular word from a column inside a text using django?

So let's say I have 3 columns.

Text | Subject | connector

Cancer is caused by windmills.| cancer, windmill| caused by

These are all saved inside a postgreSQL database. How do I highlight the words, cancer and windmill (from subject) and caused by (from connector), inside the text and display it on the webpage?

{% if db.cause and db.connector in db.text %}
<td><mark>{{ db.text }}</mark></td>

But this highlights the whole text instead of those 4 words cancer, windmill and caused by.

Update from @selcuk's suggestion:

in templatetags/filters.py:

@register.filter
def highlight(text, search):
    highlighted = text.replace(search, '<mark>{}</mark>'.format(search))
    return mark_safe(highlighted)

in page.html:

{% for db in context %}
  {% if db.cause and db.connector in db.text %}
  {% with cause=db.cause %}
  <td style="word-wrap: break-all">{{ db.text|highlight:cause }}</td>
  {% endwith %}
  {% else %}
  <td style="word-wrap: break-all">{{ db.text }}</td>
  {% endif %}

End result: Nothing is highlighted and no error messages.

Desired Output: Only Cancer, caused by and windmill to be highlighted

Upvotes: 1

Views: 551

Answers (1)

Fel
Fel

Reputation: 61

Replace() has been changed to re.sub because replace() is unable to handle case insensitive words/characters.

In templatetags/filters.py:

from django import template
from django.utils.safestring import mark_safe
import re

register = template.Library()

@register.filter
def highlight(text, search):
    search = re.split((" "), search)

    for i in search:
        highlighted = re.sub(i, '<span style="background-color: #000FF">{}</span>'.format(i), text, flags=re.IGNORECASE)
        text = highlighted
    return mark_safe(text)

Upvotes: 2

Related Questions