O'Reilly logo

Text Processing with Ruby by Rob Miller

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Evaluating Templates

We’ve looked at ERB from the perspective of writing templates. Once we’ve created a template, though, we need to know how to evaluate it and capture its output, and how to pass data into it.

Let’s first take a look at how we can load a simple template and get its output.

Simple Templates

Since ERB is part of Ruby’s standard library, it’s just a require away; we don’t need to install a third-party gem. Once we’ve required it, we use it by creating an ERB object for each of our templates, passing in the template content. We then execute the template and capture the resulting string. For example:

erb/simple-template.rb
 
require ​"erb"
 
 
template = ​"The time is <%= Time.now.strftime('%T') %>"
 
 
renderer = ERB.new(template) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required