Ruby on Rails Layouts - Ruby on Rails

What are Rails layouts?

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.

What is the process for creating layout?

The process involves defining a layout template and then letting the controller know that it exists and to use it.

Let us start by creating the template. Add a new file called standard.html.erb to app/views/layouts. You let the controllers know what template to use by the name of the file, so following a same naming scheme is advised.

Add the following code to the new standard.html.erb file and save your changes −

Everything you just added were standard HTML elements except two lines. The stylesheet_link_tag helper method outputs a stylesheet <link>. In this instance, we are linking style.css style sheet. The yield command lets Rails know that it should put the html.erb for the method called here.

Now open book_controller.rb and add the following line just below the first line −

It instructs the controller that we want to use a layout available in the standard.html.erb file. Now try browsing books that will produce the following screen.

Layout

How to add Style Sheet

Rails is using the default style sheet as we have not created any style sheet til now. Now let's create a new file called style.css and save it in /public/stylesheets. Add the following code to this file.

Refresh your browser to see the difference −

Layout example

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Ruby on Rails Topics