Lesson Monday

We're ready to start adding ERB files to our code. We'll start by adding a layout file. This file will contain HTML that's used in all our views. Remember that we want to keep our code DRY, so we shouldn't repeat ourselves. It makes sense to extract repeated code and put it into a single file.

If you haven't already, add a views folder to the root directory of the project. A view is pretty much exactly what it sounds like — content that the user will see.

All of our views will use the ERB format. It should be fairly clear why. Browsers render HTML so we need to use HTML for our views. However, since we are using Ruby, we will want access to Ruby variables, loops and so on. That's why we need the embedded Ruby part.

We'll start by creating a basic layout file called layout.erb, which should be added to the views directory. Here's the content for our layout.erb file:

views/layout.erb
<!DOCTYPE html>
<html>
  <head>
    <title>All Sales Vinyl</title>
    <link 
      rel="stylesheet" 
      href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" 
      integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
  </head>
  <body>
    <div class="container">
      <%= yield %>
    </div>
  </body>
</html>

We add Bootstrap, a title and so on. This is all basic HTML except for one line:

<%= yield %>

yield is a special Ruby keyword. It's a more advanced Ruby concept so we won't get into it here. However, be aware that yield comes from Ruby, not Sinatra. Note that expression tags <%= %> need to be used. If execution tags are used, no views will render.

Sample Layout File


views/layout.erb
<!DOCTYPE html>
<html>
  <head>
    <title>All Sales Vinyl</title>
    <link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css'>
  </head>
  <body>
    <div class="container">
      <%= yield %>
    </div>
  </body>
</html>

Lesson 16 of 37
Last updated August 7, 2022