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
end

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 = %(
  <html>
    <body>
      <h1>Messages for <%= name %></h1>
      <ul>
        <% messages.each do |message| %>
          <li><%= message %></li>
        <% end %>
      </ul>
    </body>
  </html>
)

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 = ERB.new(template).result(binding)
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:

<html>
  <body>
    <h1>Messages for Ruby Monstas</h1>
    <ul>
      <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>
    </ul>
  </body>
</html>

… 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.