Active nav link bootstrap using rails
Seems like “there’s a gem for this” have the same tone when mobile apps starting to be a hit. There is a gem for this specific problem, active_link_to, but for learning, why not we try to hard code the solution.
Lets assume that you have 2 routes you want to link in the navbar, that is Home(root_path) and About(about_path).
Referring from getbootstrap navbar example, you may see the following code snippet
<li class="active">
<a href="#">Link <span class="sr-only">(current)</span></a>
</li><li>
<a href="#">Link</a>
</li>
There are 2 problem here, one is the class active at li and the span tag with class sr-only. After some googling, it is strongly advised to keep the span for screen reader accessibility purposes.
Tackling the first problem is easy. We can use current_page helper to know what page we are currently on.
<li class="<%= 'active' if current_page?(root_path) %>">
<a href="#">Home <span class="sr-only">(current)</span></a>
</li><li>
<a href="<%= 'active' if current_page?(about_path) %>">About</a>
</li>
Next the span part, link_to can pass a block of code and content_tag can generate any html that we want.
<li class="<%= 'active' if current_page?(root_path) %>">
<%= link_to root_path do %>Home
<%= (content_tag :span, "(current)", :class => "sr-only") if current_page?(root_path) %>
<% end %>
</li><li>
<%= link_to about_path do %>About
<%= (content_tag :span, "(current)", :class => "sr-only") if current_page?(about_path) %>
<% end %>
</li>
Voila. How did i do? is there any anything i can improve? hit me up at twitter or comment below.