Optional Sidebars

For one of my projects, my layout includes optional sidebars on either side. I want to design this without tables.. so at first I thought something like this:

RUBY:
  1. <div id="leftside">
  2. <%= render :partial => "left_#{@controller.action_name}" %>
  3. </div>
  4. <div id="rightside">
  5. <%= render :partial => "right_#{@controller.action_name}" %>
  6. </div>

SO for index page, it will render the partials _left_index.rhtml and _right_index.rhtml ... but say if you don't want a side bar, then it can't find one... and you get an error. I would like to not have to resort to setting variables @left_sidebar =true @right_sidebar = false and have to do something like this:

RUBY:
  1. <% if @rightsidbar_on %>
  2. <div id="rightside">
  3. <%= render :partial => "right_#{@controller.action_name}" %>
  4. </div>
  5. <% end %>

Ideally I'd like a render_if_exist but I don't see anything like that in rails. Ideas??

Update

Almost as soon as I finished the post and sent to my friend Peter.. I decide to google for "render_partial_if_exists" and found this blog posting by Jeremy Hubert -- the exact solution! Peter was also in the process of adding a comment at the same time telling me with nearly the same solution. -- Check out Jeremys post, its awesome.

Leave a Comment