Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different layout for controller with respond_to in Rails

I understand I can call the render method with layout: 'my_layout' to change the layout within a controller method. However, some of my controller methods have the following so that I can easily render JSON as well:

respond_to do |format|
  format.html
  format.json { render json: @cars }
end

How do I change the layout for format.html? Should I replace format.html with render layout: 'my_layout'? Is there an option I can pass to format.html?

like image 453
at. Avatar asked Feb 11 '14 23:02

at.


1 Answers

By default Rails will use app/views/layouts/application.html.erb as the layout. If you want to use another layout, create app/views/layouts/my-new-layout.html.erb then

In your controller method:

respond_to do |format|
  format.html { render layout: 'my-new-layout' }
  format.json { render json: @cars }
end

Here's the relevant section in the Rails Guide: Layouts and Rendering: Options for Render

like image 130
franksort Avatar answered Sep 21 '22 10:09

franksort