Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a specific layout for all controllers within a class or module. (Rails 3)

I have the following controllers under a Admin class (or module?)

class Admin::PostsController < ApplicationController
  layout 'admin'
  # controller methods...
end

class Admin::CommentsController < ApplicationController
  layout 'admin'
  # controller methods...
end

How can I define the layout in one place for these controllers in the Admin class? Do I need to make a new file for the Admin class and define it there? I have a feeling it's some thing like this (tried but din't work).

class Admin < ApplicationController
 layout 'admin'
end

Currently all controllers scoped to the admin class are located 'app/controllers/admin/'. If I need to create the Admin class file should it be inside that folder as well or in the one above? Or is the solution super simple and am I over thinking it?

like image 694
Moudy Avatar asked May 17 '11 17:05

Moudy


People also ask

How do you use nested layouts Rails?

Rails provides us great functionality for managing layouts in a web application. The layouts removes code duplication in view layer. You are able to slice all your application pages to blocks such as header, footer, sidebar, body and etc.

What is the layout in Ruby on Rails?

A layout defines the surroundings of an HTML page. It's the place to define a common look and feel of your final output. Layout files reside in app/views/layouts. The process involves defining a layout template and then letting the controller know that it exists and to use it.

How can you tell Rails to render without a layout?

By default, if you use the :text option, the text is rendered without using the current layout. If you want Rails to put the text into the current layout, you need to add the layout: true option.


1 Answers

Try creating a BaseController class, like this, then extending your other controllers to use it:

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

Then you would have:

class Admin::PostsController < Admin::BaseController
  # controller methods...
end
like image 76
muffinista Avatar answered Oct 17 '22 06:10

muffinista