Monday, 2 April 2012

Dynamic sidebar in rails layout


Today, I am sharing common code that i usually used to set my layout.
My layout contains conditionally sidebar, some action contain sidebar some are not.S
  • One of the way is to create 2 layout file one with no sidebar and one for with sidebar.
  • Other way is one layout file and conditionally set sidebar content.
In this post i am explaining one layout with conditionally sidebar.

I am using grid system, you can use any class who sets width of sidebar.

So my layout file contains
 <div class="grid_16">
  <div class="<%= main_content_css_class%>">
   <%= yield %>
  </div>
  <div class="<%= sidebar_css_class%>">
   <%= yield :sidebar %>
  </div>
</div>
Now my application helper contains

module ApplicationHelper
  def sidebar_enabled?
    current_page = "#{controller.controller_name}.#{controller.action_name}"
 
    current_controller = controller.controller_name
 
    pages = %w(some_controller,some_controller.specific_action)

    return pages.include?(current_page) || pages.include?(current_controller)
  end
  def main_content_css_class
    sidebar_enabled? ? "grid_12" : "grid_16"
  end

  #Returns the CSS class for the 'sidebar' div depending on sidebar requirement
  def sidebar_css_class
    sidebar_enabled? ? "grid_4" : "dont-show"
  end
end
So basically sidebar_enabled? contain list of controller or controller.action_name in which sidebar is required.

You can use reverse way if your layout contains more sidebar.

I hope this is helpful for setting up layout.