layoutを使い分ける
Ruby on Rails v3.2.11
HTMLで表示をする場合、デフォルトのlayoutとしてapp/views/layouts/内のapplication.html.erbが使用されます。1つのRailsアプリケーション内で、複数のlayoutを使い分けたくなった場合のやり方についてのメモ。
renderする際にlayoutを指定
controllerの中でrenderする際にlayoutを指定できます。デフォルトのlayoutとは別のlayoutとしてapp/views/layouts/にanother_layout.html.erbを用意した場合、このように書きます。
respond_to do |format| format.html { render :layout => "another_layout"} end
controllerごとlayoutを指定
1つのcontrollerの中で(すべてのaction共通で)another_layoutを使うように指定することもできます。
class UserController < ApplicationController layout "another_layout" def index ... end
layoutを使いたくない場合
また、layoutを使いたくない場合もあります。例えば、ajaxリクエストを使用して部分的なHTMLを送出する場合などです。layoutを使わない場合は下のようにすればOKです。
respond_to do |format| format.html { render :layout => nil } end