Open jamesarosen opened 13 years ago
On RoR 3.1:
require 'action_view/template/handlers/handlebars'
ActionView::Template.register_template_handler(:hbs, ActionView::Template::Handlers::Handlebars.new)
require 'handlebars'
class ActionView::Template::Handlers::Handlebars
def call(template)
<<-RUBY_CODE
template = Handlebars.compile('#{template.source}');
vars = {}
partial_renderer = @view_renderer.send(:_partial_renderer)
vars.merge!(@_assigns)
vars.merge!(partial_renderer.instance_variable_get('@locals'))
vars.merge!(partial_renderer.instance_variable_get('@options')[:context] || {})
template.call(vars.as_json).html_safe
RUBY_CODE
end
end
Just place your .hbs
template in the same view directories as other views (just like a regular erb) and enjoy
I had some errors with the above and made a couple of modifications:
require 'handlebars'
class ActionView::Template::Handlers::Handlebars
def call(template)
<<-RUBY_CODE
template = Handlebars::Context.new.compile('#{template.source}');
vars = {}
partial_renderer = @view_renderer.send(:_partial_renderer)
vars.merge!(@_assigns)
vars.merge!(local_assigns)
# vars.merge!(partial_renderer.instance_variable_get('@options')[:context] || {})
template.call(vars.as_json).html_safe
RUBY_CODE
end
end
This is using a HandleBars::Context instance rather than Handlebars global; and local_assigns rather than @locals. I'm not sure how to fix the @options.
I have a handlebars-rails template handler that supports partials and more. https://github.com/cowboyd/handlebars-rails
@jamesarosen any chance you can give me the keys to the rubygem?
@wycats is the only owner on Rubygems; he'll have to do it.
@cowboyd you are now an owner!
See the following for a good example:
I just forked the project to give this a go. I'll update with findings as I go.