Layout and views

Extract common view component into layout


In our previous phase, if you notice in both of index.erb and cast.erb files, you will see some common code. We can extract the page layout related common code in Sinatra through Layout feature.

Common layout

Create a layout file layout.erb under views directory and add the common HTML content from both which looks as follows:

<!DOCTYPE html>
<html>
  <head>
    <meta charset='UTF-8' />
    <title>Voting App</title>
    <link rel="stylesheet" href="css/style.css">
  </head>
  <body>
    <h1><%= @title %></h1>
    <%= yield %>
  </body>
</html>

In general Layout is used to define the HTML structure of the web page.

Update the views files

Update the views files index.erb and cast.erb as follows:

  • index.erb file:

    <!-- Remove html, title and body tags -->
    <p>What's for dinner?</p>
    
    <form action='cast' method='post'>
      <ul>
        <% CHOICES.each do |id, text| %>
          <li>
            <label>
              <input type='radio' name='vote' value='<%= id %>' id='vote_<%= id %>' />
              <%= text %>
            </label>
          </li>
        <% end %>
      </ul>
    
      <button type='submit'>Cast this vote!</button>
    </form>
    
  • cast.erb file:

    <!-- Remove html, title and body tags -->
    <p>You cast: <%= CHOICES[@vote] %></p>
    <p><a href='/results'>See the results!</a></p>
    

Now, if you reload the web app (https://localhost:4567) and cast the vote, you will get the same experience as before.

Help me to improve BRG Trainings.