5.1. Menus and Sidebars

The simple tab-like menu or sidebar is the most common user interface element on the Web. In this section, you'll see how to create a simple menu using some HTML and Rails-supported logic.

5.1.1. Single-Level Menus

Rails, unsurprisingly, has some built-in-support for the logic needed to manage a menu list. The logic involved is to simply display a link to another page unless that page is the active page, in which case do something else — usually display the text without the actual link. The Rails method is link_to_unless_current, and you use it in a menu something like this:

<li>
  <%= link_to_unless_current "Home",
   {:controller => "recipes", :action => "home"} %>
</li>
<li>
  <%= link_to_unless_current "Recipes",
    {:controller => "recipes", :action => "index"} %>
</li>
<li>
  <%= link_to_unless_current "Categories",
    {:controller => "recipes", :action => "categories"} %>
</li>
<li>
  <%= link_to_unless_current "Authors",
    {:controller => "recipes", :action => "authors"} %>
</li>
<li>
  <%= link_to_unless_current "Community",
    {:controller => "recipes", :action => "community"} %>
</li>
<li>
  <%= link_to_unless_current "Gear",
    {:controller => "gear", :action => "index"} %>
</li>

This is a drop-in replacement for the Navigate sidebar in the recipes.html.erb layout file. Because you're going to want this to become rather generic, put this code in a partial — I call mine app/views/shared/_navigation_sidebar.html.erb. Then you can drop in the call from the layout file like ...

Get Professional Ruby on Rails™ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.