开发者

rails 3: layout for namespaced routes

I've created a number of controllers & views under an 'admin' namespace, but they are still pulling from the application layout. ho开发者_JS百科w can I make a layout that applies to all the views in the namespaced routes, and still use the current layout for the other pages?


I usually have a Base controller class in my namespace, and then have all controllers in that namespace inherit from it. That allows me to put common, namespace specific code in Base and all the controllers in that namespace can take advantage. For example:

class Admin::BaseController < ApplicationController
  layout 'admin'
  before_filter :require_admin_user
end

class Admin::WidgetsController < Admin::BaseController
  # inherits the 'admin' layout and requires an admin user
end


Generally speaking, Rails will use the application layout if there isn't a layout that matches the controller. For example, if you had a PeopleController, Rails would look for layouts/people.html.erb and if it didn't find that, application.html.erb.

You can explicitly specify a specific layout if you want to override this convention.

class Admin::PeopleController
  layout 'some_layout'
end

That controller will then use some_layout.html.erb rather than looking for people.html.erb and application.html.erb.

But this might be a better way if you're looking to group things: If you have a base AdminController that inherits from ApplicationController, you can have your, say, Admin::PersonController inherit from the AdminController and it will inherit the admin layout.

I don't know the specifics of your code, but you might have:

class AdminController
  def show
    #render a template linking to all the admin stuff
  end
end

app/controllers/admin/people_controller.rb:
class Admin::PeopleController < AdminController
  #your awesome restful actions in here!
end

views/layouts/admin.html.erb:
Hello from the Admin!
<%= yield %>

The one thing to realize is that Admin::PeopleController will inherit any actions that AdminController has defined (just as anything defined in ApplicationController becomes available in all sub-classes). This isn't generally a problem since you'll likely be overwriting the methods anyway, but just to be aware of it. If you don't have an AdminController, you can make one with no actions just for the purposes of the layout.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜