How to get Twitter-Bootstrap navigation to show active link?
Just made an answer on the very same question here Twitter Bootstrap Pills with Rails 3.2.2
<ul class="nav">
<li class="<%= 'active' if params[:controller] == 'controller1' %>"> <a href="/link">Link</a> </li>
<li class="<%= 'active' if params[:controller] == 'controller2' %>"> <a href="/link">Link</a> </li>
<li class="<%= 'active' if params[:controller] == 'controller3' %>"> <a href="/link">Link</a> </li>
</ul>
You can use something like (very similar to what @phil mentioned, but a little shorter):
<ul class="nav">
<li class="<%= 'active' if current_page?(root_path) %>"><%= link_to "Home", root_path %></li>
<li class="<%= 'active' if current_page?(about_path) %>"><%= link_to "About", about_path %></li>
<li class="<%= 'active' if current_page?(contact_path) %>"><%= link_to "Contact", contact_path %></li>
</ul>
https://github.com/twg/active_link_to
<%= active_link_to 'Users', users_path, :wrap_tag => :li %>
#=> <li class="active"><a href="/users">Users</a></li>
I used a helper to implement this in the style of Rails' form helpers.
In a helper (e.g. app/helpers/ApplicationHelper.rb
):
def nav_bar
content_tag(:ul, class: "nav navbar-nav") do
yield
end
end
def nav_link(text, path)
options = current_page?(path) ? { class: "active" } : {}
content_tag(:li, options) do
link_to text, path
end
end
Then, in a view (e.g. app/views/layouts/application.html.erb
):
<%= nav_bar do %>
<%= nav_link 'Home', root_path %>
<%= nav_link 'Posts', posts_path %>
<%= nav_link 'Users', users_path %>
<% end %>
This example produces (when on the 'users' page):
<ul class="nav navbar-nav">
<li><a href="/">Home</a></li>
<li><a href="/posts">Posts</a></li>
<li class="active"><a href="/users">Users</a></li>
</ul>