Jamgreen
Jamgreen

Reputation: 11039

Active menu item in node.js and express

I am using node.js, express and express-handlebars. I have a menu in the top of my layout.

In my server.js, I set all the pages with

app.locals.pages = [
  { title: 'Home', link: '/' },
  { title: 'About', link: '/about' },
  { title: 'Contact', link: '/contact' },
];

and in the layout file, I print the pages with

{{#each pages}}
  <li class="nav-item">
    <a class="nav-link" href="{{link}}">{{title}}</a>
  </li>
{{/each}}

but I want to add a class to the menu item which is currently being active.

How can I save which of the 3 menu items is active?

Upvotes: 1

Views: 5140

Answers (3)

Shayan
Shayan

Reputation: 966

I haven't tested this for your code, but I think it should work. When using handlebars, you can try this

Ember.Handlebars.helper('isSelected', function(v1,v2, options) {
    if (v1 && v2) {
        return new Ember.Handlebars.SafeString("active");
    }else{
        return new Ember.Handlebars.SafeString("nav-item");
    }
});

and on your codes
on your node js

router.get('/', function( req, res ){
  var pageData = {};
  pageData.page_link = 'home';
  res.render('template_page', pageData );
});

on your template

{{#each page in pages}}
  <li class="{{isSelected page.link  page_link }}">
    <a class="nav-link" href="{{page.link}}">{{page.title}}</a>
  </li>
{{/each}}

Again, I haven't test this. but handlebars helper work fine with HTML elements.

Upvotes: 0

lortschi
lortschi

Reputation: 4323

I solved it without to pass params over the router request. Just simple created a js file to nav partial, pass the active path of the location to the nav item and add an active class.

(function($) {
   $(document).ready(function() {
      // get current URL path and assign 'active' class
      var pathname = window.location.pathname;
      $('.nav.navbar-nav > li > a[href="'+pathname+'"]').parent().addClass('active');
  });
})(jQuery);

Upvotes: 3

Mohit Bhardwaj
Mohit Bhardwaj

Reputation: 10083

You can pass a body_id (or any other name) parameter from your routes to your views e.g.

router.get('/', function( req, res ){
  var pageInfo = {};
  pageInfo.body_id = 'homepage';
  // assign more parameters relevant for this view here
  res.render('home_page', pageInfo );
});

Now, in your view file, assign the body_id as the id of body i.e.

body(id= typeof body_id === "undefined" ? "body_id" : body_id)

Now, you can manage the active links in your css as

body#home_page .nav_item:nth-child(1),
body#about_page .nav_item:nth-child(2),
{
  background-color: red;
  /* more css styles that you want to give to your active menu item */
}

Upvotes: 2

Related Questions