Lesson Monday

We've experimented with building a basic Sinatra application that renders strings. While that was good practice for routing, it's not helpful for making an actual web application that renders HTML.

We'll use a Ruby template engine called Embedded Ruby (ERB for short) to combine Ruby code with HTML. ERB is also commonly used with Rails so we'll be using it regularly for the rest of the Ruby/Rails course.

Embedded Ruby


Embedded Ruby processes combined Ruby/HTML code, translating it to pure HTML so it can be used in the browser. Here's an example:

<h1>A List of Favorite Things</h1>
<ul>
  <% @things.each do |thing| %>
    <li><%= thing.name %></li>
  <% end %>
</ul>

Some of this code is already familiar; it's just HTML. We can use HTML normally in an ERB file. However, there's also Ruby code in the snippet above:

<% @things.each do |thing| %>
  <%= thing.name %>
<% end %>

We've removed the <li> to reduce it to ERB and Ruby elements. The code above is a simple loop and renders the name of each thing in a list of @things.

ERB uses the following tags to denote Ruby code:

<% %>

These are execution tags. They should be used for code that will not be rendered onscreen. <% @things.each do |thing| %> is an example. It's code we want to execute but it doesn't result in an expression.

<%= %>

These are expression tags. We'll use them when we want to render the result of an expression. For instance, we'll want <%= thing.name %> to render; otherwise, the names of our favorite things won't show up onscreen.

There are a few other ERB tags, but these two are the most common and the only ones we will need.

In the next lesson, we'll begin adding ERB files to our record store application. As we learn how to use ERB files further, it's important to remember that ERB is just a format that combines Ruby and HTML.

Embedded Ruby (ERB for short) is a Ruby template engine to combine Ruby code with HTML.

Here's an example:

<h1>A List of Favorite Things</h1>
<ul>
  <% @things.each do |thing| %>
    <li><%= thing.name %></li>
  <% end %>
</ul>

Execution tags are used for code that won't be rendered:

<% %>

Expression tags are used for code that should be rendered onscreen:

<%= %>

Lesson 15 of 37
Last updated August 7, 2022