Running erb templates from the command line
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.
1 2 #!/usr/bin/ruby 3 # Quick and dirty template processing script. It takes 4 # as an argument the name of the first template script 5 # and then executes it to standard output. 6 7 require "erb" 8 9 10 class QuickTemplate 11 attr_reader :args, :text 12 def initialize(file) 13 @text = File.read(file) 14 end 15 def exec(args={}) 16 b = binding 17 template = ERB.new(@text, 0, "%<>") 18 result = template.result(b) 19 # Chomp the trailing newline 20 result.gsub(/\n$/,'') 21 end 22 end 23 24 def erb(file, args={}) 25 QuickTemplate.new(file).exec(args) 26 end 27 28 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
1 2 ruby erb_run.rb main.thtml
The main template
1 2 <html> 3 <head> 4 </head> 5 <div> 6 <%= erb("title.thtml") %> 7 </div> 8 </html>
and the sub template title.thtml
1 2 <title> This is Alex's cool restraunt</title>