public
Created — forked from tizoc/tpl.rb

  • Download Gist
tpl.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
# -*- coding: utf-8 -*-
 
module Tpl
def self.new(template, variables = [], output_method = :concat)
template = template.dup
m = Module.new
start = template.index("<%")
 
render_definition = ["def self.render(__v = {}, __o = '');"]
render_definition += variables.map{|v| "#{v} = __v[:#{v}];"}
compile(template, output_method, render_definition)
render_definition << "__o; end"
m.module_eval render_definition.join
 
m
end
 
def self.compile(template, output_method, render_definition)
i = 0
len = template.length
 
until i == len
start = template.index("<%", i)
 
unless start
render_definition << "__o.#{output_method}(#{template[i..len].inspect});"
return
end
 
render_definition << "__o.#{output_method}(#{template[i...start].inspect});"
 
stop = template.index("%>", start)
i = stop + 2
 
case template[start + 2]
when "=" then
render_definition << "__r = (#{template[start+3..stop-1]}).to_s; __o.#{output_method}(__r);"
when "#" then
# ignore, # is a comment
else
render_definition << "#{template[start+3..stop-1]};"
end
end
end
end
 
tpl = Tpl.new("The sum is <%=2+2%> Also substitute <%=myfield%> ok", %w(myfield))
puts tpl.render({:myfield => 10})
tpl2 = Tpl.new("ñañaña")
puts tpl2.render
tpl3 = Tpl.new("Testing loops: <% 3.times do %> * <% end %>")
puts tpl3.render

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.