Best way to assign active class to the menu item on main menu

Generally in main menu, when user clicks on menu item, the page is navigated to href of that item and active class is assigned to its <li> element to highlight it as current page. how can i achieve such in meteor using iron router and on dynamically generated menu items ?

<ul class="dropdown-menu">
  ...
  <li class="{{#if currentRouteIs 'home'}}active{{/if}}">
    <a href="/">Home</a>
  </li>
  ...
</ul>
Template.registerHelper('currentRouteIs', function (route) { 
  return Router.current().route.getName() === route; 
});
1 Like

how can i use this with links that are fetched from database where url are dynamically generated and relatively unknown to the programmer?

Can you please post some code? I don’t clearly see how you fetch Iron Router routes from a database.

Instead of using Router.current().route.getName(), you could use Router.current().params, which returns an array of the parameters in the URL.

Here is the Template Code for the links i am generating

<ul>
	{{#each posts}}
		<li> <a href="posts/{{_id}}">{{title}}</a></li>
	{{/each}}
</ul>

Here is the template Helper code to return posts to my template

posts: function(){
return Posts.find();
}

Here is the route code

Router.route('/posts/:_id', {
name: 'posts.detail',
controller: 'HomeController',
action: 'detail',
where: 'client'
});

When user click on the link i want to add active class to the <li> of the post list

Try this code in the HTML:

<ul>
    {{#each posts}}
        <li {{#if isCurrent _id}}><a href="posts/{{_id}}">{{title}}</a></li>
    {{/each}}
</ul>

In the client Javascript code:

Template.registerHelper('isCurrent', function (id) { 
    return Router.current().params._id === id; 
});

Thank you it works… :smile:

Man, this is pure genius. I’ve been struggling with this for 2 days now. It worked like a charm with this solution
Thank you

1 Like