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.
Creating Responses
There are three ways to create an HTTP response from the controller’s point of view:
- Call render to create a full response to send back to the browser
- Call redirect_to to send an HTTP redirect status code to the browser
- Call head to create a response to end back to the browser
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.
<%= yield %>
Relation between Rails Layouts and Templates
When a request is made in an application, following process occur:
- First of all, Rails find a template for corresponding action to render method in your controllers action.
- Then finds correct layout to use.
- It uses action template to generate a content specific to the action.
- Finally it looks for the layout’s yield statement and insert action’s template here.
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
Example:
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.
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<%= yield %>
</body>
</html>
Step 2 Go to app/layouts directory and create lay.html.erb file.
- <!DOCTYPE html>
- <html>
- <head>
- <title>Layout Example</title>
- </head>
- <body>
- <h1>Layout Example</h1>
- <%= yield %>
- <p>www.javatpoint.com</p>
- </body>
- </html>
Step 3 Insert it into app/controllers/users_controller.rb file by writing following code.
- class UsersController < ApplicationController
- before_action :set_user, only: [:show, :edit, :update, :destroy]
-
- layout "lay"
-
- def index
- code....
Step 4 Run it on browser.
Leave a Reply