Rails 3,如果它存在,呈现给定控制器的部分?

JP *_*shy 5 ruby-on-rails

在我的application.html.erb应用程序布局中,我希望有一个部分呈现给定视图是否存在.例如.

如果访问者在http://example.com/users/show,我希望部分/users/_sidebar.html.erb渲染.

但如果访问者说http://example.com/user/locations/san_francisco,我想要部分/users/locations/_sidebar.html.erb渲染.

所以这里的事情是,如果该控制器/动作没有部分,它将在我的共享目录中呈现一些通用的部分,而我宁愿不用content_for块知道每块视图乱丢?

有什么想法吗?

Ala*_*ody 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
Run Code Online (Sandbox Code Playgroud)

  • 拯救所有异常将隐藏您想了解的其他异常。这会导致难以调试的错误。考虑诸如“rescuse ActionView::NoTemplateError”之类的东西(或者当没有模板时引发的任何错误)。 (6认同)