Skip to content

Instantly share code, notes, and snippets.

@mislav
Created March 21, 2011 15:00
Show Gist options
  • Save mislav/879575 to your computer and use it in GitHub Desktop.
Save mislav/879575 to your computer and use it in GitHub Desktop.
How to render Haml, Erb templates with a layout
%h1&= title
%p Hello world
<title><%= title %></title>
<body><%= yield %></body>
!!!
%title&= title
%body
= yield
require 'haml'
require 'erb'
class Hash
def to_binding(object = Object.new)
object.instance_eval("def binding_for(#{keys.join(",")}) binding end")
block = block_given? ? Proc.new : nil
object.binding_for(*values, &block)
end
end
templates = %w[layout.erb index.haml]
locals = { :title => 'Render test' }
result = templates.reverse.inject(nil) do |previous, filename|
template = File.read(filename)
context = locals.to_binding { previous }
case File.extname(filename)
when '.haml'
Haml::Engine.new(template, :filename => filename, :format => :html5).to_html(context)
when '.erb'
ERB.new(template).result(context)
else
raise "don't know how to handle template: #{filename.inspect}"
end
end
puts result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment