Tips for adjusting the "active" navigation class across various pages using base.html

I have my main navigation bar located in the base.html file and I include it in all other pages. However, I currently have the class "active" assigned to the home page link, causing it to remain active on all other pages as well.

<ul class="navbar-nav">
    <li class="nav-item">
        <a class="nav-link active" href="http://127.0.0.1:8000/backend/">
            <i class="ni ni-shop text-primary"></i>
            <span class="nav-link-text">Dashboard</span>
        </a>
    </li>
    <li class="nav-item">
        <a class="nav-link" href="http://127.0.0.1:8000/backend/clientes">
            <i class="ni ni-ungroup text-orange"></i>
            <span class="nav-link-text">Clients</span>
        </a>
    </li>
</ul>

Is there a way for me to dynamically change the active class to reflect the current page's menu item?

Answer №1

When it comes to your query, there is no universal solution that fits every situation. The answer truly varies based on the specific structure and URL hierarchy of your project. However, in most cases, implementing a custom template tag that accepts the request as an argument (along with other context variables or constants based on your project's unique logic) can be the ideal approach to calculate the current "section" and adjust the navigation bar accordingly.

Answer №2

Submit name as a variable along with the value of active.

def index(request):
   # insert your code here


    context = {

        'dashboard': 'active',
    }

    return render(request, 'index.html', context)

def clients(request):
   # insert your code here


    context = {

        'clients': 'active',
    }

    return render(request, 'clients.html', context)

Utilize the variables in this manner:

<ul class="navbar-nav">
    <li class="nav-item">
        <a class="nav-link {{ dashboard }}" href="http://127.0.0.1:8000/backend/">
            <i class="ni ni-shop text-primary"></i>
            <span class="nav-link-text">Dashboard</span>
        </a>
    </li>
    <li class="nav-item">
        <a class="nav-link {{ clients }}" href="http://127.0.0.1:8000/backend/clientes">
            <i class="ni ni-ungroup text-orange"></i>
            <span class="nav-link-text">Clients</span>
        </a>
    </li>
</ul>

Answer №3

CHOICE 1 To implement dynamic active bar logic in Django, you can utilize context processors. Add the following code snippet to your settings.py:

TEMPLATES = [
{
     #other settings
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
     #other settings
    'OPTIONS': {
        'context_processors': [
             #other options
            'context_file_path.defaults',

        ],
    },
},

Then, create a file named context_file.py and include the following function:

def defaults(request):
    active_bar = "" # Add your logic for determining the active bar here
    return {
        'active_bar': active_bar,
    }

This method allows each request to determine which bar is active, with the active_bar variable passed to your template. In your template, you can add an active class if the active_bar variable matches the name of your bar. For example:

<ul class="navbar-nav">
        <li class="nav-item">
          <a class="nav-link {% if active_bar == 'dashboard' %}active{% endif %}" href="http://127.0.0.1:8000/backend/">
            <i class="ni ni-shop text-primary"></i>
            <span class="nav-link-text">Dashboard</span>
          </a>
        </li>
        <li class="nav-item  {% if active_bar == 'clients' %}active{% endif %}">
          <a class="nav-link" href="http://127.0.0.1:8000/backend/clientes">
            <i class="ni ni-ungroup text-orange"></i>
            <span class="nav-link-text">Clients</span>
          </a>
        </li>
      </ul>

CHOICE 2

If you prefer an alternative approach, you can create a custom JavaScript file to handle the active pane functionality. This file can detect the URL and apply the active class to the corresponding list pane based on the URL.

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

"Utilizing a flexible grid system in Bootstrap to create 2 or

I am looking to create a layout with a variable number of columns using row span. Specifically, I want 3 columns on XS, 2 columns on SM (with the first 2 columns stacked on top of each other), and 3 columns on LG. I am unsure how to make the row span respo ...

The dropdown menu fails to function when placed within a div or generated dynamically

When I try to utilize the "dropdown-menu" outside of a div, it works correctly. However, when it is placed inside a div or added dynamically, it does not work as intended. Here is an example on jsfiddle The code snippet is as follows: <link rel="s ...

Dynamic updating of scores using Ajax from user input

My goal is to design a form that includes three "Likert Scale" input fields. Each of these three inputs will have a total of 10 points that can be distributed among them. The submit button should become enabled when the score reaches 0, allowing users to s ...

overlay the text at the top of a div

Looking to create an overlapping effect with text in a div, similar to the example shown in the image. I am currently utilizing Bootstrap, but open to using CSS as well. However, I need the text to go slightly underneath the overlapping element. View the ...

Managing the vertical positioning of grid items: tips and tricks

Is there a way to make the hexagons in my grid responsive to the layout, so that their height and width remain fixed relative to their container? Currently, they are overflowing from the grid container as shown in this jsfiddle: https://jsfiddle.net/gv5wc1 ...

Is there a way to generate multiple iterations of a model with a single form submission?

Below are the models I am working with: class EventType(models.Model): name = models.CharField(max_length=128) class Event(models.Model): event = models.ForeignKey(EventType, null=True, blank=True) name = models.CharField(max_length=128) ...

Discover the steps for incorporating the substring method into JavaScript to manipulate input strings

Is there a way to extract the specified portion of text from an input string using HTML and Javascript? <!DOCTYPE html> <html> <body> <input type="text" value="exampleString"></input> <button onclick=& ...

Enhancing list item appearance by replacing bullets with Font Awesome icons

I need to create a list similar to this example https://i.sstatic.net/w84xS.png Although I successfully replaced the bullet with a fontawesome icon, the result is not quite right as shown here https://i.sstatic.net/yqnbJ.png You may notice a difference ...

Send form using ajax technology

I am in the process of developing a website using GitHub pages and Jekyll. One of the key features I want to include is a contact form that allows users to send emails. To implement this functionality, I have decided to use Formspree. After creating an ac ...

Tips on arranging text around an image to prevent any overlapping

CLICK HERE FOR THE ISSUE This is the outcome. I prefer the text to be separate from the image. ...

Content duplication occurs when sharing information

After clicking the share button on a user's link, the post is successfully shared but appears twice. Upon inspecting through Firebug, it reveals two POST requests being triggered when the button is clicked once, resulting in duplicate posts being inse ...

Chrome and Firefox failing to render background property in CSS

I encountered an issue with my HTML code that I tested on both Chrome and Firefox. The background color of the first div is not displaying correctly in either browser. .box-orange { // without any position declaration background: orange; heigh ...

Arranging search outcomes in Django REST framework

I have implemented a search API for my website using Django Rest Framework. When searching for a name (e.g. "jumanji"), there may be multiple results due to various reasons. I want the search results to be ordered by either the "rating" field or the "relea ...

Steps for resolving the CSS problem with the dynamic jquery category filter

I have developed a dynamic jquery category filter, but when I choose an option, the search results page displays content with unwanted spaces between them. It seems like there is excessive distance between each piece of content. $(document).ready(functi ...

Design a universal web service indicator akin to an "activity indicator" that works seamlessly across all web browsers

My web service is quite database-heavy (using PHP and mySQL), resulting in the user being faced with a blank screen for several seconds. When a user clicks a link on an HTML page, a javascript function is triggered, which then initiates an AJAX call to in ...

Variations in Angular scope variable behavior

Code Snippet in HTML <input ng-model="test1.param"> <input ng-model="test2"> Code Snippet in Controller $scope.test1 = { param: null }; $scope.test2 = null; Upon entering text in both input fields: The value of $scope.test1.param changes ...

Utilize a personalized container for the slider's thumb within a React application

Is it possible to replace the slider thumb with a custom container/div in React instead of just styling the thumb or using a background image? I have found a codepen example that demonstrates what I am trying to achieve, but unfortunately I am having trou ...

How can PHP be used to display a varying number of items in a slider depending on the size of the screen?

I am currently utilizing media queries to adjust the layout of my website. My query is: How can I display a different number of items in a slider based on the screen size? For small screens, I have included the following code: <?php if($i == 4) {echo ...

Determine the size of v-flex in Vue / Vuetify

Vuetify provides the v-resize directive, which is demonstrated in an example using window size. I am interested in utilizing this directive to monitor the size of a specific component (e.g. v-flex). In the provided codesandbox example, the objective is t ...

What is causing this code to keep iterating endlessly?

I have a basic jquery script embedded in my HTML code that utilizes the cycle plugin for jQuery. The problem I'm facing is that when I interact with the slideshow using the "next" or "previous" buttons, it continues to loop automatically after that in ...