Skip to content

Instantly share code, notes, and snippets.

@cyx
Forked from tizoc/tpl.rb
Created August 18, 2011 04:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cyx/1153295 to your computer and use it in GitHub Desktop.
Save cyx/1153295 to your computer and use it in GitHub Desktop.
# -*- 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