Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 849
Aen Tan Avatar asked Apr 20 '11 11:04

Aen Tan


2 Answers

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.

like image 171
dogenpunk Avatar answered Nov 18 '22 09:11

dogenpunk


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.

like image 7
Peter Kovacs Avatar answered Nov 18 '22 09:11

Peter Kovacs