Chapters 14 & 15 - Web Apps

Exercise 2: ERB templates

Below is a Sinatra app meant to show items in an HTML “unordered list” (the <ul> element). There are two routes.

require 'sinatra'

get('/fruits') do
  @items = ["apples", "oranges", "pears"]
  erb :list
end

get('/meats') do
  @items = ["chicken", "beef", "lamb"]
  erb :list
end

The /meats route should render HTML like this, showing a list of meats:

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <ul>
        <li>chicken</li>
        <li>beef</li>
        <li>lamb</li>
    </ul>
  </body>
</html>

…And the /fruits route should render nearly-identical HTML, but with a list of fruits.

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <ul>
        <li>apples</li>
        <li>oranges</li>
        <li>pears</li>
    </ul>
  </body>
</html>

Both routes store arrays in the @items instance variable. And both routes rely on the below ERB code, which is stored in the list.erb file within the views subfolder, to render the list.

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <ul>
      <% @items.each do |item| %>
        <li><%= item %></li>
      <% end %>
    </ul>
  </body>
</html>