Templating with ERB

Templating systems let you separate the presentation and logic of your application.

So far, we’ve looked at using Ruby to create HTML output, but we can turn the problem inside out: we can actually embed Ruby in an HTML document. The embedded Ruby (or ERB) library is included with Ruby’s standard distribution.

Embedding Ruby in HTML is a powerful concept—it gives us the equivalent of a scripting tool such as PHP, but with the full power of Ruby.

Using ERB

ERB is a filter. Input text is passed through untouched, with the following exceptions:

ExpressionDescription

<% ruby code %>

This executes the Ruby code between the delimiters. Any resulting value isn’t sent to the output.

<%= ruby expression %>

This evaluates the Ruby expression ...

Get Programming Ruby 3.3 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.