Approx 3 minutes read

Recently while working on a Rails project, I came across following markup for navigation:

 1 <ul class="sidebar-menu">
 2   <li class="treeview active">
 3     <a href="#">
 4       <span>Category</span>
 5     </a>
 6     <ul class="treeview-menu">
 7       <li class="active">
 8 	      <a href="#">
 9 	      	<span>Add Category</span>
10 	      </a>
11       </li>
12       <li>
13 	      <a href="#">
14 	      	<span>Update Category</span>
15 	      </a>
16       </li>
17     </ul>
18   </li>
19 </ul>

Note that in above markup, for each active menu item, there is a parent active element. For example, when “Add Category” (line number 7) is active, it’s parent element “Category” is also active (line number 2).

To incorporate this in Rails, I decided to make parent element as controller and child elements as actions for that controller. Thus for above markup, I created a categories controller and added action new, create, edit and update to it. Then I created two helper functions as below:

1 module ApplicationHelper
2 	def controller?(*controller)
3 		controller.include?(params[:controller])
4 	end
5 
6 	def action?(*action)
7 		action.include?(params[:action])
8 	end
9 end

Then I created the menu layout as below:

 1 <ul class="sidebar-menu">
 2   <li class="treeview <%= 'active' if controller?('categories') %>">
 3     <a href="#">
 4       <span>Category</span>
 5     </a>
 6     <ul class="treeview-menu">
 7       <li class="<%= 'active' if controller?('categories') && action?('new', 'create') %>">
 8       <%= link_to(raw('<span>Add category</span>'), new_categories_path) %>
 9       </li>
10       <li class="<%= 'active' if controller?('categories') && action?('update', 'edit') %>">
11       <%= link_to(raw('<span>Modify category</span>'), edit_categories_path) %>
12       </li>
13     </ul>
14   </li>
15 </ul>

This layout perfectly synchronized the navigation links with pages.

I found this as a neat way of making navigation in my rails project. You can also use current_page? (documentation) method to accomplish the same. There are many gems also available out there to build the navigation in Rails. You can have a look at them here.

comments powered by Disqus