Skip to content

@cyx /tpl.rb forked from tizoc/tpl.rb
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
# -*- 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.