Firstly, I have passed an object {navSelectTitle : "your-required-page-to-be-selected"}
while rendering each page in the main app.js
. Then, you can create a list in your ejs template like following:
<% const navItems = ["home", "articles", "videos", "audios"] %>
Then, you can loop through the list and add a class to make the link appear selected. (Here, I have used the class class="selected"
to make the link appear selected)
Also, since I need my home page to have the href as href="/"
and not <a href="/home"
, I have created a separate if statement for the case of "home" to accomodate this special case.
<% navItems.forEach(navlink => { %>
<% if(navlink == navSelectTitle) { %>
<% if (navlink == "home") {%>
<li class="links selected"><a href="/"><%= navlink %></a></li>
<% } else {%>
<li class="links selected"><a href="/<%= navlink %>"><%= navlink %></a></li>
<% } %>
<% } else { %>
<% if (navlink == "home") {%>
<li class="links"><a href="/"><%= navlink %></a></li>
<% } else {%>
<li class="links"><a href="/<%= navlink %>"><%= navlink %></a></li>
<% } %>
<% } %>
<% }) %>
The code logic goes as follows:
- Loop through the list.
- If the list item equals to the object value that you passed while rendering the page, then the
li
tag will have the class="selected"
. If not, the else statement will create a normal link without the selected class.
- To accomodate the case where the home link should have
href="/"
, there's a nested if-else statement inside the if statement for the said case.
NOTE: Using partial for the navigation bar can help dry your code and makes this logic a little convenient.