Over a million developers have joined DZone.

Running Erb Templates From The Command Line

·
The following script takes the name of a template as it's argument. Within the
template the command erb 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.


#!/usr/bin/ruby
# 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 = File.read(file)
   end
   def exec(args={})
      b = binding
      template = ERB.new(@text, 0, "%<>")
      result = template.result(b)
      # Chomp the trailing newline
      result.gsub(/\n$/,'')
   end
end

def erb(file, args={})
   QuickTemplate.new(file).exec(args)
end

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 args. 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 title.thtml This is Alex's cool restraunt
Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}