A layout is a view file which surrounds the templates and we can use the layout across many controller and actions too.
We have a file application.html.erb in views/layouts which is default layout to all the templates in the application. We can even use different rails layouts for different controllers and actions also.
We have a controller
class UsersController def index end def new end end
If we create a layout with the name users.html.erb(as same as the controller name) in the view/layout folder. By default, the users’ controller uses this ruby on rails layout. This Layout is called Controller Specific Layout.
Like this, we can create individual layouts for all the controllers if the controller didn’t find the layout with a name as it is, then it uses the default application.html.erb.
Sometimes we come across the situation where we need to choose the layout dynamically, means depends on the condition the layout has to be chosen.
In the following example, we have two types of logins one is the user and the other is the admin. When admin logins one layout has to be rendered and when user logins another has to be rendered. Follow the example code for this rails render layout.
class UsersController layout :choose_layout def index end def new end protected def choose_layout if current_user.admin? “admin” elseif current_user.user? “user” else “application” end end end
If you want to tell your controller to use a specific layout then use the following code in your controller
class UsersController layout “my_layout” end
If you want to tell the controller to don’t use any layout then write the code like this.
class UsersController layout nil end
Layout to an Action:
If you want to use a particular rails application layout to a particular action write the code like this
class UsersController def index render :layout => 'my_layout' end end
Rails set layout in action never goes wrong. We can even choose false if don’t want any layout to a particular action
class UsersController def index render :layout => false end end
Some of the useful keywords on layouts
class UsersController layout “my_layout”, : only => :method_name layout “my_layout”, :except => [ :my_method1, :my_method2 ] layout :my_layout, : only => :my_method end
There are lots of ways to specify the layout just we need to define the layouts in views and use them when they needed. The ruby on rails layout templates is incredible.