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) ... |
Get Text Processing with Ruby now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.