在我的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块知道每块视图乱丢?
有什么想法吗?
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)