ERB: Embedding Ruby in HTML

David Morales David Morales
/
A sheet of paper with hand-drawn geometric shapes and scattered red rubies, reflecting light on a table.

HTML is the essential piece to creating content for the web, but it’s a static markup language without backend logic. Historically, developers have embedded backend logic into HTML templates using technologies like Microsoft’s ASP or PHP. Ruby offers a similar solution called ERB, short for “Embedded Ruby.”

How to Use ERB Templates for Dynamic HTML

ERB allows Ruby code to be embedded directly within HTML templates. Here’s an example that list tasks for a project:

<html>
<body>
<h1>Tasks for project: <%= project_name %></h1>
<ul>
<% tasks.each do |task| %>
<li><input type="checkbox"> <%= task %></li>
<% end %>
</ul>
</body>
</html>

Here’s how it works:

So, if we remove the HTML markup and leave only the ERB content, it would be equivalent to the following:

puts project_name
tasks.each do |task|
puts task
end

Rendering ERB Templates in Ruby: Step-by-Step Example

Let’s look at a complete Ruby script that shows how ERB templates are rendered:

require 'erb'
template = %(
<html>
<body>
<h1>Tasks for project: <%= project_name %></h1>
<ul>
<% tasks.each do |task| %>
<li><input type="checkbox"> <%= task %></li>
<% end %>
</ul>
</body>
</html>
)
project_name = 'Fitness tracking app'
tasks = ['Check pending pull requests',
'Deploy new features to staging',
'Update project documentation']
html = ERB.new(template).result(binding)
puts html

This script outputs:

<html>
<body>
<h1>Tasks for project: Fitness tracking app</h1>
<ul>
<li><input type="checkbox"> Check pending pull requests</li>
<li><input type="checkbox"> Deploy new features to staging</li>
<li><input type="checkbox"> Update project documentation</li>
</ul>
</body>
</html>

Note that the Ruby code was processed and the variables were used.

Test your knowledge

  1. What does ERB stand for in Ruby?

  1. Which ERB tag executes Ruby code without directly outputting anything to HTML?

  1. What does the <%= ... %> ERB tag do?

  1. What is the purpose of the binding parameter in ERB?

  1. What will the Ruby method ERB.new(template).result(binding) return?