ruby templating the easy way:
#!/usr/bin/ruby -w
require 'erb'
module MW
module Utils
module Template
ENDL = "\n"
#
# compiles the given template
#
def self.compile(template, locals={})
# create code for easyaccess locals
local_code = "<% " << ENDL
for key in locals.keys
local_code << "#{key} = locals[:#{key}]" << ENDL
end
local_code << "%>" << ENDL
template = local_code << template
puts template
# compile template
erb = ERB.new(template, 0, "%<>")
compiled = erb.result(binding)
compiled.gsub(/\n$/,'') # chomp the trailing newline
end
end
end
end
#
# test 1
#
t = "hi <%= firstname %> <%= lastname %>"
puts MW::Utils::Template.compile(t, :firstname=>"peter", :lastname=>"meier")
puts MW::Utils::Template.compile(t, :firstname=>"marcus", :lastname=>"wendt")
#
# test 2
#
class TestUser
attr_accessor :first, :last
end
u = TestUser.new
u.first = "peter"
u.last = "meier"
t = "hallo <%= user.first %> <%= user.last %>"
puts MW::Utils::Template.compile(t, :user=>u)
Tags
+opensource
+ruby
+snippets