我有不同的命名空间控制器,它们共享相同的布局:
# /app/controllers/admin/dashboard.rb
class Admins::DashboardController < ApplicationController
...
end
# /app/controllers/clients/dashboard.rb
class Clients::DashboardController < ApplicationController
...
end
这是我的目录结构:
App
|_ Controllers
| |_ Admins
| | |_ dashboard_controller.rb
| |_ Clients
| |_ dashboard_controller.rb
|
|_ Views
|_ Admins
| |_ Dashboard
| |_ index.html.erb
|
| |_ show.html.erb
|_ Clients
| |_ Dashboard
| |_ index.html.erb
| |_ show.html.erb
|_ layouts
|_ admin.html.erb
|_ _sidebar.html.erb
我想确定布局是按
Admins
还是Clients
显示,以便显示正确的侧边栏,例如:<% if admins? %>
...
<% elsif clients? %>
...
<% end %>
这是否也是解决此问题的最佳方法,还是有更好的解决方案?
最佳答案
您可以使用模板继承来实现。只需在要重用的布局中render 'sidebar'
并在以下位置定义_sidebar模板:
app/views/admins/dashboard/_sidebar.html.erb # for Admins::DashboardController
app/views/clients/dashboard/_sidebar.html.erb # for Clients::DashboardController
app/views/application/_sidebar.html.erb # fallback sidebar
由于模板继承,Rails会自动为您选择右侧边栏。
如果您还想在其他Admin / Client控制器中使用相应的侧边栏,则还可以为每个控制器使用BaseController,如下所示:
class Admins::BaseController < ApplicationController
end
class Admins::DashboardController < Admins::BaseController
...
end
现在在
_sidebar.html.erb
中有一个app/views/admins/base/
模板,并确保Admins命名空间中的每个Controller都继承自Admins :: BaseController。您将看到,这为所有命名空间控制器的通用功能/回调等结构提供了一种非常好的方法。此外,它还允许您在需要时覆盖侧边栏部分,只需将
_sidebar.html.erb
文件放在任何更特定的视图路径中即可,例如app/views/admins/myspecificsidebars/_sidebar.html.erb
。