Skip to content

Instantly share code, notes, and snippets.

@judofyr
Created December 11, 2009 21:50
Show Gist options
  • Save judofyr/254546 to your computer and use it in GitHub Desktop.
Save judofyr/254546 to your computer and use it in GitHub Desktop.
$:.unshift 'lib'
$:.unshift '../mustache/examples'
require 'temple'
require 'pp'
require 'benchmark'
require 'simple'
# A pretty basic Mustache engine
class MustacheEngine < Temple::Engine
parser :Mustache
filter :Mustache
filter :Escapable
generator :Interpolation
# We could also use:
# compiler :StringBuffer
# compiler :ArrayBuffer
# compiler :Array
#
# Or, if you wrote your own:
# use MyOwnCompiler
end
# An example of how an ERB-engine would look. (Yes, it works.)
class ERBEngine < Temple::Engine
parser :ERB
filter :DynamicInliner
generator :ArrayBuffer
end
# Read the source
content = File.read(Simple.template_file)
# Compile it.
code = MustacheEngine.new.compile(content)
puts code
# Inject into Mustache.
Simple.template.instance_eval "def render(ctx); #{code}; end"
puts Simple.render
"Hello #{CGI.escapeHTML(ctx[:name].to_s)}\nYou have just won $#{CGI.escapeHTML(ctx[:value].to_s)}!\n#{ if v = ctx[:in_ca]
v = [v] if v.is_a?(Hash) # shortcut when passed a single hash
if v.respond_to?(:each)
ctx1 = ctx.dup
begin
r = v.map { |h| ctx.update(h); "Well, $#{CGI.escapeHTML(ctx[:taxed_value].to_s)}, after taxes.\n" }.join
rescue TypeError => e
raise TypeError,
"All elements in {{in_ca}} are not hashes!"
end
ctx.replace(ctx1)
r
else
"Well, $#{CGI.escapeHTML(ctx[:taxed_value].to_s)}, after taxes.\n"
end
end
}"
Hello Chris
You have just won $10000!
Well, $6000.0, after taxes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment