Navigation menu in Ruby on Rails
Recently while working on a Rails project, I came across following markup for navigation:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<ul class="sidebar-menu">
<li class="treeview active">
<a href="#">
<span>Category</span>
</a>
<ul class="treeview-menu">
<li class="active">
<a href="#">
<span>Add Category</span>
</a>
</li>
<li>
<a href="#">
<span>Update Category</span>
</a>
</li>
</ul>
</li>
</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
2
3
4
5
6
7
8
9
module ApplicationHelper
def controller?(*controller)
controller.include?(params[:controller])
end
def action?(*action)
action.include?(params[:action])
end
end
Then I created the menu layout as below:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<ul class="sidebar-menu">
<li class="treeview <%= 'active' if controller?('categories') %>">
<a href="#">
<span>Category</span>
</a>
<ul class="treeview-menu">
<li class="<%= 'active' if controller?('categories') && action?('new', 'create') %>">
<%= link_to(raw('<span>Add category</span>'), new_categories_path) %>
</li>
<li class="<%= 'active' if controller?('categories') && action?('update', 'edit') %>">
<%= link_to(raw('<span>Modify category</span>'), edit_categories_path) %>
</li>
</ul>
</li>
</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.