public
Created

  • Download Gist
1-welcome_controller.rb
Ruby
1 2 3 4 5 6
class WelcomeController < ApplicationController
def index
@foo = "FROM CONTROLLER"
@user = User.first
end
end
2-index.html.hbs
Handlebars
1 2 3 4
<h1>Welcome#index</h1>
<p>Find me in app/views/welcome/index.html.erb</p>
<p>{{foo}}</p>
<p>{{{rails "link_to" user/name user}}}</p>
3-output.textile
Textile

4-impl.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
require 'v8'
 
class HandlebarsTemplateHandler
 
def self.js
Thread.current[:v8_context] ||= begin
V8::Context.new do |js|
js.load(File.join(Rails.root, 'vendor', 'javascripts', 'handlebars.js'))
js.eval("Templates = {}")
end
end
end
 
def self.rails_helper
Thread.current[:v8_rails_helper] ||= begin
js.eval(%{
(function(helper) {
var params = Array.prototype.slice.call(arguments, 1);
var av = this.__context__.fallback.actionview;
return av[helper].apply(av, params);
})
})
end
end
 
def self.call(template)
# Here, we're sticking the compiled template somewhere in V8 where
# we can get back to it
js.eval(%{Templates["#{template.identifier}"] = Handlebars.compile(#{template.source.inspect}) })
 
%{
js = HandlebarsTemplateHandler.js
fallback = { :actionview => self, :rails => ::HandlebarsTemplateHandler.rails_helper }
js.eval("Templates['#{template.identifier}']").call(assigns, fallback)
}
end
end
 
ActionView::Template.register_template_handler(:hbs, HandlebarsTemplateHandler)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.