I’m still a beginner with ruby and rails, and now I’m googling about methods for creating a tabbed menu, marking the list element of the currently active controller with a css class “current”. There are many hits on google, but I haven’t found any that I manage to get working.
I have my menu here:
<ul>
<li class="current"><%= link_to 'Home', root_path %> </li>
<li><%= link_to 'Browse songs', page_path('browse') %> </li>
<li><%= link_to 'Add song', new_song_path %> </li>
<li><%= link_to 'Request song', artists_path %> </li>
<li><%= link_to 'My ReChord', artists_path %> </li>
<li><%= link_to 'Help', page_path('help') %> </li>
<li id="search"><form><input type="search" placeholder="Type here to find a song or an artist"/></form> </li>
<li class="notab">
<% if user_signed_in? %>
<%= link_to 'Sign out', destroy_user_session_path %>
<% else %>
<%= link_to 'Sign in', new_user_session_path %> or
<%= link_to 'sign up', new_user_registration_path %>
<% end %>
</li>
</ul>
Now I have class=”current” hard coded on the Home tab. However, when clicking for example Browse songs, I want the class=”current” to be moved to the corresponding list element for that line.
Note that I have some links that just is the route path (like new_song_path) and some links that are sub pages, like page_path(‘help’). I need it to work for both these types of links.
Can you provide me with either a good tutorial suitable for my two days long experience with rails, or (preferably) example code that might fit perfectly on my list above? Thanks in advance!
If you want something more flexible, checkout the tabs_on_rails plugin I created to solve exactly this common pattern.
In your template use the
tabs_taghelper to create your tab.The example above produces the following HTML output.
The usage is similar to the Rails route file. You create named tabs with the syntax
tab.name_of_tab.The name you use creating a tab is the same you’re going to refer to in your controller when you want to mark a tab as the current tab.
Now, if the action belongs to
DashboardController, the template will automatically render the following HTML code.