Rendering ERB

The Ruby code embedded in our template uses two local variables (or methods) with the names name and messages. Also, each is called on messages, so this should probably be an array:

puts name

messages.each do |message|
  puts message

So how do we provide these objects to the ERB template? And how do we execute the whole thing?

It’s probably best to look at an example:

require "erb"

template = %(
      <h1>Messages for <%= name %></h1>
        <% messages.each do |message| %>
          <li><%= message %></li>
        <% end %>

name = "Ruby Monstas"
messages = [
  "We meet every Monday night at 7pm",
  "We've almost completed the beginners course!",
  "Feel free to come by and join us!"

html =
puts html

Does this code make sense to you?

Let’s walk through it:

If you run this code it will output something like this:

    <h1>Messages for Ruby Monstas</h1>
      <li>We meet every Monday night at 7pm</li>
      <li>We've almost completed the beginners course!</li>
      <li>Feel free to come by and join us!</li>

… which is a valid HTML document that a browser would render (display) like this:

Looks good?

To recap, all that our code above does is the following:

In other words, it executes (we say “renders”) the ERB template using the name and messages objects, and returns the HTML as a result.