Reputation: 570
I have the following bootstrap menu (pills) defined in a partial:
<ul class="nav nav-pills">
<li class="active"><a href="#">Home</a></li>
<li><a href="#">Menu 1</a></li>
<li><a href="#">Menu 2</a></li>
</ul>
Here are some sample routes:
get 'institute/:institute_id/students' => 'students#index' , as: 'students_of_institute'
get 'students/:student_id' => 'students#show'
I have referenced this partial in various views. How do I dynamically change the current active tab?
Upvotes: 3
Views: 3582
Reputation: 11494
An alternative to @Uzbekjon's solution is to use the current_page?
helper method. The first argument is the controller, the second (optional) is the action.
Since your navigation links will be top-level links, you will usually not need to specify the action. That way, you will still have an active pill for sub-pages in the same controller.
E.g:
<ul class="nav nav-pills">
<li class="<%= 'active' if current_page? controller: :students %>">
<%= link_to 'Students', students_path %>
</li>
</ul>
I think this is slightly more elegant.
Upvotes: 5
Reputation: 11813
You'd have to check the current path and if it matches your link's add an active
class to your li
.
An easy way would be to compare params[:controller]
and params[:action]
.
For example:
# GET /posts
params[:controller] => "posts"
params[:action] => "index"
Here is a "dirty" example. It's better to move it out to some helper:
<ul class="nav nav-pills">
<li class="<%= 'active' if params[:controller] == 'students' && params[:action] == 'index' %>"><%= link_to 'Students', students_path %></li>
</ul>
Upvotes: 5