Ruby on Rails - Ruby On Rails Layout- ruby on rails tutorial - rails guides - rails tutorial - ruby rails
What is Layout in Ruby On Rails
- In Rails, layouts are pieces that fit together (for example header, footer, menus, etc.) to make a complete view.
- 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.
- The process involves defining a layout template and then letting the controller know that it exists and to use it. First, let's create the template.
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 necessary 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:
Learn Ruby On Rails Tutorials - Ruby On Rails Layout - Ruby On Rails Examples - Now in this application, we will insert a layout file.
- 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.
Learn Ruby On Rails Tutorials - Ruby On Rails Layout Step2 - Ruby On Rails Examples
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.