DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Running Erb Templates From The Command Line

  • submit to reddit
        The following script takes the name of a template as it's argument. Within the
template the command <b>erb</b> is in scope to call more templates. I wrote this for a friend who was having hell with NVU templates and I suggested to write the code by hand and use this script to build his static pages.

# Quick and dirty template processing script. It takes
# as an argument the name of the first template script
# and then executes it to standard output.

require "erb"

class QuickTemplate
   attr_reader :args, :text
   def initialize(file)
      @text =
   def exec(args={})
      b = binding
      template =, 0, "%<>")
      result = template.result(b)
      # Chomp the trailing newline

def erb(file, args={})

puts erb(ARGV[0])

The erb command itself takes an optional argument of a hash which is passed to the template as the
variable name <b>args</b>. Thus you can parameterize your sub templates. 

Call the command as

ruby erb_run.rb main.thtml

The main template

    <%= erb("title.thtml") %>

and the sub template <b>title.thtml</b>

<title> This is Alex's cool restraunt</title>


Snippets Manager replied on Sun, 2012/04/22 - 3:46am

Hi, I extended this code to get the binding from Facter[1], which is a tool used by Puppet[2] to fill in the variables in ERB templates based on system information (e.g. FQDN or hostname). This in turn allowed me to reuse my Puppet ERB templates in external, non-Ruby programs such as Fabric[3]. Long story short... do you mind releasing this code under, say, FreeBSD license, so that I can legally extend and distribute it? I'll publish the modified code here, obviously. [1] [2] [3]