简体   繁体   English

控制器的不同布局与Rails中的respond_to

[英]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. 我知道我可以使用layout: 'my_layout'调用render方法layout: 'my_layout'来改变控制器方法中的布局。 However, some of my controller methods have the following so that I can easily render JSON as well: 但是,我的一些控制器方法具有以下内容,因此我也可以轻松地呈现JSON:

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

How do I change the layout for format.html ? 如何更改format.html的布局? Should I replace format.html with render layout: 'my_layout' ? 我应该更换format.htmlrender layout: 'my_layout' Is there an option I can pass to format.html ? 我可以将一个选项传递给format.html吗?

By default Rails will use app/views/layouts/application.html.erb as the layout. 默认情况下,Rails将使用app/views/layouts/application.html.erb作为布局。 If you want to use another layout, create app/views/layouts/my-new-layout.html.erb then 如果您想使用其他布局,请创建app/views/layouts/my-new-layout.html.erb

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 以下是Rails指南中的相关部分: 布局和渲染:渲染选项

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM