Leveraging the power of ExpressJs to incorporate a dynamic Navbar onto

ExpressJS and EJS are my chosen technologies for creating Views.

When it comes to the navigation bar, I want to add a class="active" to the links that represent the current page. However, if I use partials in my views, how can I achieve this?

Here is a quick example:

Index.ejs

<ul class="nav navbar-nav navbar-right">
        <li><a class="active" href="/Index">Home</a></li>
        <li><a href="/About">About</a></li>
        <li><a href="/Work">Work</a></li>
</ul>

About.ejs

<ul class="nav navbar-nav navbar-right">
        <li><a href="/Index">Home</a></li>
        <li><a class="active" href="/About">About</a></li>
        <li><a href="/Work">Work</a></li>
</ul>

Work.ejs

<ul class="nav navbar-nav navbar-right">
        <li><a href="/Index">Home</a></li>
        <li><a href="/About">About</a></li>
        <li><a class="active" href="/Work">Work</a></li>
</ul>

This is my current method of handling active links in the navbar by including it on each page individually

Is there a more efficient approach where I don't have to render the navbar every time I create a new page?

Answer №1

To make the "active" route value accessible in the partial template, you can pass it as a local variable like this:

<%- include('partial/nav', {active: "About"}); %>

Next, use the active variable to determine the "active" class within the nav partial template:

<ul class="nav navbar-nav navbar-right">
     <li><a <%if(active=="Home"){%>class="active"<%}%> href="/Index">Home</a></li>
     <li><a <%if(active=="About"){%>class="active"<%}%> href="/About">About</a></li>
     <li><a <%if(active=="Work"){%>class="active"<%}%> href="/Work">Work</a></li>
</ul>

For a similar approach, check out this resource

Answer №2

To properly load your navigation, follow these steps:

<script>
$("#header").load("header.ejs");
</script>

Next, extract the URL of the current page and determine the active page name. Utilize this function to apply the active class to the current page:

$(document).ready(function($){
var url = window.location.href;
$('.nav li a[href="'+url+'"]').addClass('active');
});

REMINDER: You must retrieve the page name from the URL using a specific function as it will display the complete page URL.

You only need to create the header.ejs file once and include it on each page.

We hope this guidance proves useful!

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

Issue: 'node' is not being recognized when attempting to execute the file using the package.json script

Currently diving into the world of Node.js, I encountered an issue stating "node is not recognized as an internal or external command" whenever I attempt to start my project using either npm start or npm run start. Strangely enough, running node index.js ...

Can you explain the purpose of the 'required' validator in Mongoose?

The Mongoose documentation on the required validator does not provide a clear explanation of what it actually means. It seems evident that undefined will not satisfy this validator, and values that evaluate to true (!!v) will be accepted. However, what ab ...

Troubleshooting problem with Kafka connection when broker is located in a separate Kubernetes namespace

I am currently utilizing a Node.js microservice to connect to a Kafka service. When the Kafka broker is located in the default namespace alongside the other microservices, everything runs smoothly. const kafka = new Kafka({ clientId: 'my-app', ...

Disconnected WebSocket in Node.js using Socket.io

Currently, I am encountering an issue. It involves a login page that leads to another page where my socket connection is disrupted. The goal I am striving for is: Within my server-side app.js app.post('/login', urlencodedParser, function(req, ...

Exploring the Interaction between Express.js Requests and Mongoose Models

We're currently in the process of developing a REST API alongside my colleagues using Express.js and Mongoose. As we work with certain Mongoose Model methods and statics, we find the need to have access to the Express.js Request object for additional ...

jQuery selector unable to locate the specified class in the table row

After receiving an array of strings as a response from an SQL query, I am using JavaScript to dynamically add this data as rows to an HTML table: loadUsers: function() { . . . function displayUsersOnTable(response) { for(var i = ...

Issue with jquery .height(value) function not functioning properly on Internet Explorer

I have come across a challenge with the following code snippet: var winheight = $(window).height(); var headerHt = (0.11 * winheight); $(".header").height(headerHt) The purpose of this code is to dynamically adjust the size of .header and other elements ...

Why does Heroku keep saying it cannot locate the package.json file in my module every time I attempt to do a heroku push?

After creating my own npm package by forking react-coverflow, everything seemed to work perfectly when using it locally in my app with the command "npm install react-coverflow-mod" --save. I was able to run my app smoothly by selecting "run with debug (F5 ...

The hamburger menu unexpectedly appears outside the visible screen area and then reappears at random intervals

My website has a hamburger menu for mobile devices, but there's a problem. When the page loads on a small screen, the hamburger menu is off to the right, causing side scrolling issues and white space. I thought it might be a CSS problem, but after exp ...

Seeking Assistance with Customizing HTML Uniform Panels

Looking at the HTML provided, I have two requirements: Request: I need to center the green boxes regardless of their height, without having to adjust the top:-10px/bottom:-10px values when the height changes. Eliminate the fixed top/bottom value (as the ...

Issues with starting a node application within a screen session using PHP

First things first: I am attempting to initiate a node application through PHP. I have developed a script that can verify if the node application is running, terminate it, and then start it up again. However, I am encountering some difficulty when trying t ...

What is causing fs.readFileSync to not recognize my json document?

So, I've been working on creating a Discord bot that can extract specific data from my JSON file. Here is the structure of my project: Project | +-- data/ | | | +-- compSciCourses.json | +-- src/ | | | +-- search.js | +-- bot.js | +-- t ...

What is the process of this script when initiated with an NPM build command?

I have a package.JSON file with the following scripts: "scripts": { "typings": "typings install", "build": "tsc && webpack", "watch": "npm-run-all -p -r -l tsc-watch webpack-watch", "tsc-watch": "tsc -w", "webpack-watch": "web ...

React application encounters compilation errors following the installation of Express and Cors

I've been working on a React application that's designed to fetch an mp3 file from a server, but I keep encountering a CORS error. In an attempt to resolve this issue, I followed a suggestion to enable CORS by installing express and cors using np ...

implementing node.js and express with nginx using multiple locations

I am working on hosting two separate node apps using express under a single subdomain, while having nginx handle the serving of static files. In both of my node apps, I am utilizing the following code: app.use(express.static(path.join(__dirname))); Below ...

What is the best way to customize the MenuProps of Material UI Select component using createTheme?

I'm trying to update the dropdown menu style of my Material UI Select component using createTheme, but I'm having trouble getting it to work. Here is the code I have so far. Can you spot what might be causing the issue? import { createTheme } fr ...

Ways to achieve a consistent output in Buffer.from compared to fs.readFile?

Currently, I am in the process of developing a feature for my slackbot that involves sending a post request containing binary data from an image to a ticketing system known as ServiceNow. Initially, I faced some challenges with obtaining the correct output ...

What is the best way to configure dotenv for both development and production environments?

I have incorporated dotenv in my Express JS API server by utilizing a .env file for environment setup. For both development and production environments, I prefer using the .env file. During development, I am using nodemon. If I add -r dotenv/config to pa ...

Configuring a server-side rendered Angular application on Plesk hosting platform

After successfully setting up server side rendering in my Angular app using nguniversal on my local machine, I am now facing the challenge of implementing this on a remote server with Plesk. In my local environment, I can serve the files by running: npm r ...

Retrieving information from a related collection within a parent collection using the populate() method

I have a project to create a system for recording timesheets. Each employee can log different hours for different tasks assigned to them each day. The Timesheet collection stores individual timesheet entries as an array. Here is an example of the data/sche ...