Change Rails’ layout via controller

February 18, 2008

 
No Gravatar

I’ve seen a few people asking me how to specify a specific layout in their controllers. Simple:

1
2
3
4
#my admin/condos_controller.rb
class Admin::CondosController < ApplicationController
  layout 'layouts/admin'
end
  • Will that work for RJS templates? i.e. format.js?
  • Jonathan
    I had the same problem trying to figure that out :) Glad I could help!
  • Steve
    Sweet - thanks!
    I had tried what you have in line #10 above, but it had *not* occurred to me to put what you have in line #2. Did both as you suggest and the app doesn't complain now. Thanks so much for stocking with this for me!
  • Jonathan
    Steve, this should make sense, if not, let me know.


    class DashboardController < ApplicationController
    layout 'primary'

    def index
    @everything = Stuff.find(:all)
    end

    def show
    @something = Stuff.find(params[:id])
    render :layout => "secondary"
    end

    end

  • Steve
    Jonathan - thanks! I appreciate your help and interest. I'm sorry, I don't follow which "method" you are suggesting I place that directive in. Assuming we are talking about the controller, I've got the basic 2,0 RESTful controller with at present the basic seven methods. I want all except "show" to use a common layout, but I want "show" to use a different one. When I put anything that begins with "render" inside the show method I get an error informing me that too many redirects have been requested.
  • Jonathan
    Steve, try something like this inside your method:


    render :action => "index", :layout => "help"
  • Steve
    I can't figure out how to get a specific controller method to use a different layout. Your example works at the top of the controller, but how do I get "show" to use a different layout than "new" does? "render" doesn't seem to work anymore.
blog comments powered by Disqus