Utilizing the replace() function to add a highlighting effect to text in Django 2.1

I am currently working on a unique template filter that will enhance search results by highlighting keywords, similar to how Google search results are displayed.

Here is the code for the custom filter:

register = template.Library()
@register.filter
@stringfilter
def highlight(value, search_term):
    return value.replace(search_term, "<span class='highlight'>%s</span>" % search_term)

However, the filter currently does not apply the CSS class <span class='highlight'> to the targeted word. Instead, it displays the text in the browser exactly as

<span class='highlight'>word</span>
. For example, "The most desired car brand right now is
<span class='highlight'>Tesla</span>
." How can I modify the code to actually change the CSS class of the targeted word using the replace() method?

Answer №1

The main concern lies in the necessity to autoscape when applying filters that modify HTML elements. For more information on this topic, refer to https://docs.djangoproject.com/en/2.1/howto/custom-template-tags/#filters-and-auto-escaping

Here's a sample of the code in action:

from django import template
from django.utils.safestring import mark_safe
from django.utils.html import conditional_escape
from django.template.defaultfilters import stringfilter

register = template.Library()

@register.filter(needs_autoescape=True)
@stringfilter
def highlight(value, search_term, autoescape=True):
    return mark_safe(value.replace(search_term, "<span class='highlight'>%s</span>" % search_term))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

SignalR enables the display of identical dashboard data pulled from queries on various browsers. By utilizing SignalR/hub, MVC, and C#.NET, the data can

Encountering an issue with my signalr/hub while fetching dashboard data. I'm using 2 browsers to access data based on dates. However, when searching for July on browser 1 and then switching to another month on browser 2, the data in browser 1 gets upd ...

Filtering Django template tags by slug is a useful feature that allows for

In my project, I've set up a many-to-one relationship between organizations and events. Each organization can have multiple events associated with it. I already have a template in place that displays all events filtered by city for everyone to see. Ho ...

Getting a jquery lightbox up and running

After experimenting with three different jquery plugins in an attempt to create a lightbox that appears when clicking on a link containing an image, I am currently testing out this one: . Despite adding the plugin source in the head and ensuring that the l ...

Is there a way to prevent the text box from expanding beyond the small breakpoint?

Help! I'm trying to control the size of a Bootstrap 4 input text box. I need it to stop growing after the small breakpoint, so it doesn't expand to the full width of the screen. ...

Choose items that do not contain ::before or ::after pseudo-elements

I am looking to apply a specific font style to all text on a page except for Font Icons (specifically Font Awesome) which do not share a common class. In order to achieve this, I need to target elements in one of the following ways: Elements that do not ...

Am I on the right track in my understanding of how document and viewport relate to mouse position in JavaScript?

After reviewing responses from a previous inquiry, it is evident that both pertain to the x and y coordinates of mouse positions. In relation to the document and In relation to the viewport. I have delved into an article on QuirksMode, yet I feel ther ...

Why isn't the image utilizing all the available space?

I'm working on creating a simple card to display services, with just an image and some text. However, I'm facing an issue where the image is not taking up the full width and height of the container as expected. Could someone help me figure out w ...

Troubleshooting: Issue with multiple file input elements on page - only the first input is functional and not displaying preview images

Having some trouble with loading multiple file inputs and their preview images. I've tried using getElementsByClassName but I suspect that I'm not iterating over them correctly. I want to avoid using unique IDs for the elements because they will ...

Creating a custom CSS clip to apply a rounded path on an image

I have been experimenting with applying a "clip path" to an image using a rounded path. While I am aware that SVG clip paths are an option, I found them to be less responsive. As an alternative, I attempted to place the SVG graphic under the image within a ...

Despite using twitter bootstrap, the elements on my webpage are still overlapping one another

While implementing Twitter Bootstrap on my website, I encountered a problem where elements start overlapping if the window size is reduced. This issue does not look appealing, and I expected Twitter Bootstrap to ensure that my website is fully responsive a ...

What could be causing the issue of not being able to load CSS files or images?

I'm currently in the process of learning how to develop websites, but I've encountered a stumbling block that I can't seem to overcome. I'm hoping someone here can help me out. I'm facing an issue where I am unable to link either a ...

Ways to identify changes in an HTML page following a form redirection

views.py class UpdatePasswordView(PasswordChangeView): form_class = UpdatePasswordForm success_url = reverse_lazy("login") login.html {% if passwordChanged %} <p style="color:green;">Your password has been successfu ...

Styling elements conditionally with AngularJS-controlled CSS

Looking for some guidance in Angular as a newcomer. I am attempting to adjust a style when clicked. On my page, I have multiple content spaces created using the same template. Upon clicking a "more" link, I desire to expand that specific section. I have ac ...

Exploring the capabilities of django-reversion and django-reversion-compare in conjunction with the User

Hi there, I'm facing some issues while trying to incorporate the django-reversion and django-reversion-compare modules into my project. I've started a new project and my objective is to track changes in the user_auth log using django-reversion ( ...

What is the best way to display only distinct items from a specific category in a database using Django's queryset filtering?

I am currently building a website using Django and have a database containing objects, each with a state attribute. I am trying to create a page that displays a list of unique states. However, when attempting to use the distinct function, I encounter an er ...

Eclipse now features automatic CSS class suggestions to help streamline your coding

After using NetBeans for a while, I am now considering making the switch to Eclipse. Everything seems fine, but one thing that is bothering me is that Eclipse does not provide CSS class proposals like NetBeans does. In NetBeans, whenever I use or create a ...

Some CSS features might not work properly when using Vuetify alongside Vue.js and Webpack

I believe the issue may stem from my inability to correctly import the JS file for Vuetify, but I haven't been able to pinpoint any errors. It seems that certain CSS functionalities of Vuetify, like list highlight events, are not working in my applica ...

Webpage unable to scroll

Having trouble with scrolling on my webpage and I can't figure out why! The issue is happening when trying to view this page: Within the main file, I have included 2 other php files: <?php include '../../include/menu.php'; inclu ...

What steps should I follow to set up HAProxy for server sent events compatibility?

I am currently working on integrating Server Sent Events into an established application. The challenge I face is that there may be extended periods (approximately 5 minutes) where no event is generated. I would like to set up the endpoint in a way that it ...

Connecting an image to its corresponding content through hover effect

Can someone please assist me? I am trying to create a hover effect on an image with an "add to cart" link similar to what is shown here: I seem to be having trouble with the code, could you provide some guidance? .hunderter { background: url(http ...