Rails 3, providing partial for a given controller, if it exists?

In my layout application.html.erbfor my application, I want to have a partial one that displays if it exists for the given view. eg.

If the visitor is in http://example.com/users/show, I need a partial to /users/_sidebar.html.erbdisplay.

But if the visitor said, http://example.com/user/locations/san_franciscoI would like a partial to /users/locations/_sidebar.html.erbbe displayed.

So, the point here is that if there weren’t a partial for this controller / action, it would do some common parts in my shared directory, and I would prefer not to put each view using content_forblocks that you know?

Any ideas guys?

+5
source share
2

Sean Behan :

http://seanbehan.com/programming/render-partial-if-file-exists/

:

<%= render_sidebar %>

# This method could use either the rescue or the if file exists technique.
def render_sidebar
  render(:partial => "/#{controller.name}/sidebar"
rescue
  #default side bar
end
+2

. :

  def render_partial_if_exists(base_name, options={})

    file_name           = ::Rails.root.to_s+"/app/views/layouts/_#{base_name}.html.erb"
    partial_name        = "layouts/#{base_name}"
    else_file_name      = ::Rails.root.to_s+"/app/views/layouts/_#{options[:else]}.html.erb"
    else_partial_name   = "layouts/#{options[:else]}"

    if File.exists?(file_name)
      render :partial => partial_name
    elsif (options.key?(:else) and !options[:else].nil? and File.exists?(else_file_name))
        render :partial => else_partial_name
    end
  end

, :

<%= render_partial_if_exists "page_#{controller.action_name}_sidebar", :else => "page_sidebar" %>

, "layouts/page_edit_sidebar", , "layouts/page_sidebar"

+4

All Articles