Easy templating in ruby

marcus • May 26th, 2007

ruby templating the easy way:
#!/usr/bin/ruby -w

require 'erb'

module MW
  module Utils
    module Template
      
      ENDL = "\n"
      
      #
      # compiles the given template
      #
      def self.compile(template, locals={})
        # create code for easyaccess locals
        local_code = "<% " << ENDL
        for key in locals.keys
          local_code << "#{key} = locals[:#{key}]" << ENDL
        end
        local_code << "%>" << ENDL
        template = local_code << template
  
  puts template
  
        # compile template
        erb = ERB.new(template, 0, "%<>")
        compiled = erb.result(binding)
        compiled.gsub(/\n$/,'') # chomp the trailing newline
      end
    end
  end
end


#
# test 1
#
t = "hi <%= firstname %> <%= lastname %>"
puts MW::Utils::Template.compile(t, :firstname=>"peter", :lastname=>"meier")
puts MW::Utils::Template.compile(t, :firstname=>"marcus", :lastname=>"wendt")

#
# test 2
#
class TestUser
  attr_accessor :first, :last
end

u = TestUser.new
u.first = "peter"
u.last = "meier"

t = "hallo <%= user.first %> <%= user.last %>"
puts MW::Utils::Template.compile(t, :user=>u)

Tags

+opensource +ruby +snippets
3d 4-space abstract aesthetic system aesthetics algorithm alien ambient ambisonics animation architecture art artificial audio audio research black&white book caskets classic clicks & cuts code color computer-vision conceptual art consoles cpp culture ddr design devices digtial fabrication documenta documentation drawing dynamics electricity electromagnetism electronics environment event exhibition experimental exploration fashion festival film flocking folk food fractal furniture gamedev generative genetic geometry glitch graphic hacks haptics hardware history hyperspace ideas illustration images inspiration installation instrument intelligence interactive interieur japan java knowledge management landscape library life light liquid live london math micro minimal modernism monochrome motion motion graphics multiples music naming nature nervous ink networked networking opensource osx painting paper particles performance personal photography physics playful politics press print processing processing.org programming quotes recipes research retro romance ruby scripts sculpture SENDUNG.net shopping snippets social software sound space space exploration craft space exploration craft orbiter supercollider swiss systems technology theory theremin toys transformed travel tricks typography universe video visual vj water web2.0 xcode