Rendering an ERB template with bindings from a hash

2015-06-04 · 1 min read

Let's define an erb template

my_template = <<-EOF
My name is: <%= name %>
My interests are:
<% interests.each do |el| %>
- <%= el %>
<% end %>

Our goal is to render that templated from the following hash

my_hash = {
  name: "John",
  intersts: ["programming", "computers", "logic"]

We're going to use OpenStruct to create a proper binding and pass it to ERB instance.

require 'erb'
require 'ostruct'

def erb(template, vars) { binding })

erb(my_template, my_hash)

Another approach is to inherit from OpenStruct and use its binding directly.

class ERBWithBinding < OpenStruct
  def self.render_from_hash(t, h)

  def render(template)

ERBWithBinding::render_from_hash(my_template, my_hash)

My Tech Newsletter

Get emails from me about programming & web development. I usually send it once a month