Created
March 21, 2011 15:00
-
-
Save mislav/879575 to your computer and use it in GitHub Desktop.
How to render Haml, Erb templates with a layout
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
%h1&= title | |
%p Hello world |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<title><%= title %></title> | |
<body><%= yield %></body> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
!!! | |
%title&= title | |
%body | |
= yield |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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