Cha*_*son 6 layout ruby-on-rails
我有我的主应用程序布局,但后来我的网站的/ account部分与应用程序布局markupwise具有完全相同的布局,除了/ account页面在布局的内容区域中添加了侧边栏.
我不想公然复制应用程序布局并创建几乎冗余的"帐户"布局,而是扩展应用程序布局,在内容区域添加侧边栏.
所以我的应用程序布局中有这样的东西:
<html>
<body>
<div id="content">
<%= yield %>
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
而且我要
<html>
<body>
<div id="content">
<div id="sidebar"></div>
<%= yield %>
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
有没有办法在不复制代码的情况下实现这一目标?
您可以yield在布局中放置多个,只需为其他布局添加名称:
<html>
<body>
<div id="content">
<%= yield :sidebar %>
<%= yield %>
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
您可以yield使用该content_for方法为其添加HTML
<% content_for :sidebar do -%>
<div id="sidebar"></div>
<% end -%>
Run Code Online (Sandbox Code Playgroud)
但是你必须将它添加到你想要有侧边栏的每个视图中.相反,创造views/layouts/application_with_sidebar.html.erb
<% content_for :sidebar do -%>
<div id="sidebar"></div>
<% end -%>
<%= render :file => 'layouts/application' %>
Run Code Online (Sandbox Code Playgroud)
如果您希望将yields 的数量保持在最小值,则可以嵌套布局.
视图/布局/ application.html.erb
<html>
<body>
<div id="content">
<%= yield(:with_sidebar) or yield %>
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
视图/布局/ application_with_sidebar.html.erb
<% content_for :with_sidebar do -%>
<div id="sidebar"></div>
<% end -%>
<%= render :file => 'layouts/application' %>
Run Code Online (Sandbox Code Playgroud)
控制器/ accounts_controller.rb
class AccountsController < ApplicationController
layout 'application_with_sidebar'
...
end
Run Code Online (Sandbox Code Playgroud)
如果您的 /account 路由绑定到帐户控制器,您始终可以拥有带有条件部分的全功能布局,如下所示
render :template => "/shared/sidebar" if controller.controller_name == "account"
Run Code Online (Sandbox Code Playgroud)
(我不得不承认它不讨人喜欢)