您可以在佈局多個yield
,索性放棄了額外的人一個名字:
<html>
<body>
<div id="content">
<%= yield :sidebar %>
<%= yield %>
</div>
</body>
</html>
您可以通過使用content_for
方法
爲
yield
添加HTML
<% content_for :sidebar do -%>
<div id="sidebar"></div>
<% end -%>
但是,您必須將其添加到每個您想要具有邊欄的視圖。相反,創建views/layouts/application_with_sidebar.html.erb
<% content_for :sidebar do -%>
<div id="sidebar"></div>
<% end -%>
<%= render :file => 'layouts/application' %>
Further reading
如果你更喜歡的yield
S上的數目保持在最低限度,你可以嵌套的佈局來代替。
視圖/佈局/ application.html.erb
<html>
<body>
<div id="content">
<%= yield(:with_sidebar) or yield %>
</div>
</body>
</html>
視圖/佈局/ application_with_sidebar.html.erb
<% content_for :with_sidebar do -%>
<div id="sidebar"></div>
<% end -%>
<%= render :file => 'layouts/application' %>
控制器/ accounts_controller.rb
class AccountsController < ApplicationController
layout 'application_with_sidebar'
...
end
請務必查看相同文檔的[更新版本](http://guides.rubyonrails.org/v4.0.12/layouts_and_rendering.html#using-nested-layouts)。 Rails的新版本發生了變化,鏈接的示例可能不再有效。 – 2015-07-21 13:45:21