Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I implement Section-specific navigation in Ruby on Rails?

I have a Ruby/Rails app that has two or three main "sections". When a user visits that section, I wish to display some sub-navigation. All three sections use the same layout, so I can't "hard code" the navigation into the layout.

I can think of a few different methods to do this. I guess in order to help people vote I'll put them as answers.

Any other ideas? Or what do you vote for?

like image 223
Matt Rogish Avatar asked Sep 29 '08 22:09

Matt Rogish


2 Answers

You can easily do this using partials, assuming each section has it's own controller.

Let's say you have three sections called Posts, Users and Admin, each with it's own controller: PostsController, UsersController and AdminController.

In each corresponding views directory, you declare a _subnav.html.erb partial:

/app/views/users/_subnav.html.erb
/app/views/posts/_subnav.html.erb
/app/views/admin/_subnav.html.erb

In each of these subnav partials you declare the options specific to that section, so /users/_subnav.html.erb might contain:

<ul id="subnav">
  <li><%= link_to 'All Users', users_path %></li>
  <li><%= link_to 'New User', new_user_path %></li>
</ul>

Whilst /posts/_subnav.html.erb might contain:

<ul id="subnav">
  <li><%= link_to 'All Posts', posts_path %></li>
  <li><%= link_to 'New Post', new_post_path %></li>
</ul>

Finally, once you've done this, you just need to include the subnav partial in the layout:

<div id="header">...</div>    
<%= render :partial => "subnav" %>
<div id="content"><%= yield %></div>
<div id="footer">...</div>
like image 88
Olly Avatar answered Sep 19 '22 12:09

Olly


  1. Partial render. This is very similar to the helper method except perhaps the layout would have some if statements, or pass that off to a helper...
like image 23
Matt Rogish Avatar answered Sep 20 '22 12:09

Matt Rogish