Render a template from a hash in Ruby

A hash is a great way to manage a list of key/value pairs, and templates are a great way to render content. So here’s a simple way to render a template from a hash.

template.erb

My favorite color is <%= favorite_color %>.

render.rb

require 'erb'
require 'ostruct'

opts = OpenStruct.new({
  :favorite_color => ARGV[0]
})

template = open('template.erb', 'r') {|f| f.read}
puts ERB.new(template).result(opts.instance_eval {binding})

So running

ruby render.rb blue

will output this

My favorite color is blue.

Which is cool. The interesting parts (and the reason I’m writing this) are that you need to instantiate a new OpenStruct from your hash so that its members can be accessed as methods, and then you have to set the binding for ERB by saying opts.instance_eval {binding}. This runs binding in the context of the opts object, so then calls to methods like favorite_color made by ERB in this context will evaluate to the values of our hash.

This entry was posted in ruby and tagged , , , , , , , . Bookmark the permalink.

One Response to Render a template from a hash in Ruby

  1. Pingback: Render an ERB Template from a Hash - Martin Brennan

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>