0

Boostrap makes it easy to set a navigation item "active" so that users know which page they're on (more info). How do I dynamically set/remove the "active" CSS class from the navigation item in Sails.js?

<ul class="navbar-nav ml-auto">
  <li class="nav-item active" id="map-item">
    <a class="nav-link" href="/">Map</a>
  </li>  
  <li class="nav-item active" id="faq-item">
    <a class="nav-link" href="/faq">FAQ</a>
  </li>
  <li class="nav-item active" id="contact-item">
    <a class="nav-link" href="/contact">Contact</a>
  </li>  
</ul> 

There are multiple solutions online that use plain JavaScript or AJAX but I don't know how I can imoplement that in Sails.js.

I have a layout.ejs file which defines the general layout of every page, and then I have ejs pages for Map, FAQ and contact. Ideally, it would be best to only change a single part of the code in case I decide to add more pages later on.

Cesare
  • 9,139
  • 16
  • 78
  • 130

1 Answers1

0

For a purely Sails JS solution you can do the following use req.path, reference here, to get the request URL and pass it into your view. So for example the URL is www.sailsapp.com/faq using let a = req.path in the controller will give you variable a with value of '/faq'. Then in your view you can use an if like

<li class="nav-item active" id="faq-item">
<a class="nav-link <% if (a == '/faq') {%> active <%}%>" href="/faq">FAQ</a>
</li>

You can use this logic for any of the links you wish to.