=begin
Homoplate template libray
Ugly (for now?) class to manage simple templating stuffs
REQUIREMENTS:
* nothing ! Odeley !
USAGE:
html = "
___TITLE______ARTICLES_START___ titre: ___TITRE___
___ARTICLES_END___"
articles = [ {:title => 'one'}, {:title => 'two'} ]
h = Homoplate.new( "template_file" )
h.global_vars << {:TITLE => 'My title'}
h.loop_vars[:ARTICLES] => articles
text = h.generate
=end
class Homoplate
attr_accessor :magic_key, :template, :global_vars, :loop_vars
def initialize( template_file = "template.html", global_vars = [], loop_vars = {}, magic_key = "___" )
@magic_key = magic_key
@template = template_file
@global_vars = global_vars
@loop_vars = loop_vars
@template_string = ""
end
def generate
begin
@template_string = File.open( @template ).readlines.join( "" )
rescue Exception => e
raise "Can't read template file #{@template}: #{e.to_s}"
end
#each loops_vars is a key of its Hash representing an external Hash
@loop_vars.each do |key, value|
regexp = Regexp.new( "#{@magic_key}#{key}_START#{@magic_key}(.*?)#{@magic_key}#{key}_END#{@magic_key}", Regexp::MULTILINE )
focus_array = @template_string.scan regexp
#focus_array.each { |f| f.delete_at 0 }.flatten
focus_array.flatten!
# focus = Regexp.new( "#{@magic_key}#{key}_START#{@magic_key}(.*?)#{@magic_key}#{key}_END#{@magic_key}", Regexp::MULTILINE ).match( @template_string )
# focus = ["", ""] if focus.nil?
focus_array.each do |focus|
generated_loop = ""
#here, we run our loop
value.each do |item|
item_focus = focus.dup #we'll work on that copy
#each item is a key of the external Hash mapped.
item.each do |k, v|
item_focus.gsub!( "#{@magic_key}#{k}#{@magic_key}", v )
end
generated_loop << item_focus
end
#let's replace the whole block in the template
@template_string.gsub!( "#{@magic_key}#{key}_START#{@magic_key}#{focus}#{@magic_key}#{key}_END#{@magic_key}", generated_loop )
end
end
#simple replacement on the root doc.
@global_vars.each do |h|
h.each do |key, value|
@template_string.gsub!( "#{@magic_key}#{key}#{@magic_key}", value )
end
end
@template_string
end
end