In Rails, layouts are pieces that fit together (for example header, footer, menus, etc) to make a complete view. An application may have as many layouts as you want. Rails use convention over configuration to automatically pair up layouts with respective controllers having same name.
Rails layouts basically work on Don't Repeat Yourself principle (DRY).
In Rails, layouts are enabled by default. Whenever you generate a new Rails application, a layout is automatically generated for you in app/views/layouts.
First we need to define a layout template and then define the path for controller to know that layout exists.
There are three ways to create an HTTP response from the controller's point of view:
Importance of yield statement
The yield statement in Rails decides where to render the content for the action in layout. If there is no yield statement in the layout, the layout file itself will be rendered but additional content into the action templates will not be correctly placed within the layout.
Hence, a yield statement is necessory to add in a layout file.
Relation between Rails Layouts and Templates
When a request is made in an application, following process occur:
Finding correct layout
Rails searches for the layout with same name in the app/layouts directory as the controllers name.
For example, if you have a controller called GioController, then rails will search for layouts/gio.html.erb layout. It no layout with the same name is present, then it will use the default layout app/views/layouts/appplication.html.erb
Earlier we made an example whose output is as follows:
Now in this application, we will insert a layout file.
Step 1 Go to app/layouts/application.html.erb file, remove all the code and write following code.
Step 2 Go to app/layouts directory and create lay.html.erb file.
Step 3 Insert it into app/controllers/users_controller.rb file by writing following code.
Step 4 Run it on browser.
DownloadDownload this example