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

本秂侑毒 提交于 2019-11-29 07:23:49

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.

mikewilliamson

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 %>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!