module Stack module Template attr_accessor :generator attr_accessor :basename attr_accessor :path attr_accessor :original_extension attr_accessor :extension attr_accessor :raw def initialize(path, generator = nil) self.generator = generator self.path = path self.original_extension = "html" if File.file?(path) self.basename = File.basename(path) ext = File.extname(path) self.original_extension = ext[1, ext.length] self.extension = self.original_extension read end end def read f = File.open(self.path) self.raw = f.read f.close end def render(_payload = { }, do_layout = true) _payload = template_payload.deep_merge(_payload) layout_name = _payload[:layout] if (layout_name and do_layout) # get layout _tpl_payload = self.generator.layouts[layout_name].template_payload _tpl_payload.delete(:layout) _tpl_payload.delete(:template) _tpl_payload.delete(:generator) #puts _tpl_payload.inspect #puts "\n" _payload = _payload.merge(_tpl_payload) end #puts _payload.inspect #puts "\n\n" content = Liquid::Template.parse(self.raw).render(Mash.new(_payload), Stack::Filters::Register.extensions) content = self.transform(content) if (layout_name and do_layout) _payload.delete(:layout) begin _payload = _payload.merge({ :content => content }) content = self.generator.layouts[layout_name].render(_payload) rescue => e STDERR.puts e.to_str end end return content end def template_payload { :template => self.to_hash, :generator => self.generator.to_hash }.merge(self.payload) end def payload raise InterfaceNotProvided end def to_hash { }.merge(self.payload) end def transform(content = self.raw) case self.basename when /\.textile/ self.extension = "html" RedCloth.new(content).to_html when /\.(mdown|markdown|mkdn|md)/ self.extension = "html" Maruku.new(content).to_html when /\.(less)/ self.extension = "css" Less::Engine.new(content).to_css when /\.(liquid|liq)/ self.extension = "html" else content end end def write!(content = self.render) FileUtils.mkdir_p(File.dirname(write_path)) out = File.open(write_path, "w+") out.rewind out.write(content) out.close end def write_path File.join(self.generator.target, self.write_filename) end def write_basename if self.basename self.basename.gsub(".#{self.original_extension}", "") else @write_basename ||= Digest::MD5.hexdigest(self.raw) end end def write_filename "#{write_basename}.#{self.extension}" end end end