2010-10-06 65 views
6

我有我的主應用程序佈局,但是我的網站有一個/帳戶部分,它與應用程序佈局標記具有完全相同的佈局,除了/帳戶頁面中添加了側邊欄內容區域的佈局。在Rails中擴展現有佈局

與其明顯地複製應用程序佈局並創建一個接近冗餘的「帳戶」佈局,我想擴展應用程序佈局,在內容區域添加側邊欄。

所以我有這樣的事情在我的應用程序佈局:

<html> 
<body> 

<div id="content"> 

<%= yield %> 

</div> 

</body> 
</html> 

,我想

<html> 
<body> 

<div id="content"> 

    <div id="sidebar"></div> 

    <%= yield %> 

</div> 

</body> 
</html> 

有沒有辦法做到這一點不復制的代碼?

回答

3

如果你的/帳戶路由綁定賬戶控制器,你可以隨時與條件部分包含完整的佈局像這樣

render :template => "/shared/sidebar" if controller.controller_name == "account" 

(我不得不承認,它不討好眼睛雖然)

4

對於網站的其他部分,您經常會遇到同樣的情況,在這種情況下,使用嵌套佈局可能會有意義。

http://guides.rubyonrails.org/v2.3.8/layouts_and_rendering.html#using-nested-layouts

+0

請務必查看相同文檔的[更新版本](http://guides.rubyonrails.org/v4.0.12/layouts_and_rendering.html#using-nested-layouts)。 Rails的新版本發生了變化,鏈接的示例可能不再有效。 – 2015-07-21 13:45:21

5

您可以在佈局多個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 
+0

然後我將變量放入主要的全局佈局中,該佈局不適用於網站的所有部分。只是感覺不對。感謝這個想法。 – 2010-10-06 18:29:57

+0

@Chad像@mark建議的嵌套佈局可能是最好的選擇。這一切都取決於你需要多久這個標記出現。 – 2010-10-06 19:26:03