maeshimaの日記

メモ書きです

nested layouts

Layouts and Rendering in Railsの最後の方を見て。

app/layouts/application.html.erb

<html>
  <head>
  <title><%= @page_title or 'Page Title' %></title>
  <%= stylesheet_link_tag 'layout' %>
  <style type="text/css"><%= yield :stylesheets %></style>
  </head>
  <body>
    <div id="top_menu">Top menu items here</div>
    <div id="menu">Menu items here</div>
    <div id="content"><%= yield(:content) or yield %></div>
  </body>
</html>

app/layouts/news.html.erb

<% content_for :stylesheets do %>
  #top_menu {display: none}
  #right_menu {float: right; background-color: yellow; color: black}
<% end -%>
<% content_for :content do %>
  <div id="right_menu">Right menu items here</div>
  <%= yield(:news_content) or yield %>
<% end -%>
<% render :file => 'layouts/application'  %>

やってること

content_for と render :file を使ってレイアウトをネスト。application.html.erbに大枠となるレイアウト(ヘッダーとかフッタとか)を定義して、各コントローラーで中身を切り替える。いままで一つのレイアウトファイルをひたすら使い回していたけど、これつかうとよりDRYにできそう