格式为JS时需要无布局渲染(需要烘干)

我在控制器中有这个:

respond_to do |format| format.html format.js { render :layout => false } end 

当请求是Ajax时,哪些输出没有布局。 我在许多动作和控制器中复制这个。 我该如何干这个?

我在我的应用程序控制器中使用它:

 class ApplicationController < ActionController::Base layout proc{|c| c.request.xhr? ? false : "application" } end 

其中包括.js,.json等等。

好吧,这个答案已经晚了几年,但你也可以通过将它重命名为apps/views/layouts/application.html.erb来创建你的布局作为特定于html的布局。

如果mime类型不匹配,Rails足够聪明,不会使用js响应的布局。

很有可能更新版本的rails会为你解决这个问题,但从3.0.20开始这对我有用。

尝试新的respond_with语法:

 class SomeController < ApplicationController respond_to :html, :json ... def index @things = Something.all respond_with(@things) end ... end 

虽然它看起来像是在没有布局的情况下进行渲染,但是你已经回到了以前的状态,但至少你已经在大多数动作中消除了样板。 如果您正在寻找respond_with的详细说明,请查看Jose Valim的“ Crafting Rails Applications ”。 好书!

对于非常简单的DRYing,您可以随时将respond_to块放在子例程中:

 class SomeController < ApplicationController ... def index @things = Something.all respond end def new @new_thing = Something.new respond end ... private def respond respond_to do |format| format.html format.js { render :layout => false } end end end 

另一种选择是使用以下命令创建samename.js.erb的布局文件:

 <%= yield %>