问题
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?
回答1:
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.
回答2:
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.
回答3:
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!
回答4:
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
回答5:
Another option is to create a layout file of the samename.js.erb with:
<%= yield %>
来源:https://stackoverflow.com/questions/5729476/render-without-layout-when-format-is-js-needs-drying