开发者

Render without layout when format is JS (needs drying) [duplicate]

This question already has answers here: Never render a layout in response to xhrs (3 answers) Closed 8 years ago. 开发者_StackOverflow中文版

I have this in my controllers:

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

Which outputs without layout when the request is Ajax. I'm replicating this in many actions and controllers. How do I DRY this?


I use this in my application controller:

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

Which covers .js, .json, etc. for me.


Well, this answer is a few years late, but you can also create your layout as a html-specific layout by renaming it to apps/views/layouts/application.html.erb.

If the mime-type doesn't match up, Rails is smart enough not to use the layout for js responses.

It's very possible that more recent versions of rails take care of this for you, but this works for me as of 3.0.20.


Try the new respond_with syntax:

class SomeController < ApplicationController
  respond_to :html, :json

  ...

  def index
    @things = Something.all
    respond_with(@things)
  end

  ...
end

Although it looks like to get it to render without a layout you are back to pretty much what you had before but at least you have elimnated boilerplate in most of your actions. If you are looking for a detailed explanation of respond_with, check out "Crafting Rails Applications" by Jose Valim. Great book!


For very simple DRYing, you could always just put your respond_to block in a subroutine:

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


Another option is to create a layout file of the samename.js.erb with:

<%= yield %>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜