Layouts in Ruby on Rails are surrounding webpages (HTML pages). Views can be shown combined with layouts.

Layout files are stored in app/views/layouts/. You can use a layout many times in views.

This makes your app maintainable, instead of having to change 100s of views to change the look of the app, change one layout file.

Create a layout

Create template

A layout file is a web page, a HTML template. All of these are stored in app/views/layouts, navigate there.

Add a file named standard.html.erb. Add this contents to the template:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv = "Content-Type" content = "text/html; charset = iso-8859-1" />
<meta http-equiv = "Content-Language" content = "en-us" />
<title>Rails</title>
</head>
<body id = "library">
<div id = "container">
<div id = "header">
<h1>Rails</h1>
<h3>Ruby on Rails</h3>
<hr>
</div>
<div id = "content">
<%= yield -%>
</div>
<div id = "sidebar"></div>
</div>
</body>
</html>

The next step is to map the route to the view combined with the layout. You made a weather app with route /weather/ in the previous article. If you haven’t made the app from previous article, make it.

In the controller, tell Rails to use this layout.
Open app/controllers/weather_controller.rb. Change it into:

1
2
3
4
5
6
7
class WeatherController < ApplicationController
layout 'standard'
def new
@climate = Climate.new
render 'weather/new'
end
end

Start Rails server with rails server. This will start the Rails web server on the machine.

Congratulations! If you now open /weather/ you’ll see the layout has been added to your view.