cowboyd / handlebars.rb

Ruby Bindings for Handlebars.js
http://www.handlebarsjs.com
161 stars 67 forks source link

Add Rails template handler #2

Open jamesarosen opened 13 years ago

jamesarosen commented 13 years ago

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.

jamesarosen commented 13 years ago

Also possibly of help:

GermanDZ commented 12 years ago

On RoR 3.1:

initializerz/template_handlers.rb


require 'action_view/template/handlers/handlebars'

ActionView::Template.register_template_handler(:hbs, ActionView::Template::Handlers::Handlebars.new)

 lib/action_view/template/handlers/handlebars.rb

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

mahemoff commented 12 years ago

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.

cowboyd commented 12 years ago

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?

jamesarosen commented 12 years ago

@wycats is the only owner on Rubygems; he'll have to do it.

wycats commented 12 years ago

@cowboyd you are now an owner!