5

My rails controller returns JS often, and I'm using Coffeebeans to allow me to have js.coffee views. The only problem with this is that it uses the <%= ... %> syntax for embedded Ruby... I would ideally like to use Coffeescript/HAML style string interpolation, that is: #{..} , and HAML style tags, i.e instead of <%= ... %>, just use = with proper indentation.

I would imagine this sort of syntax would best be used with file extensions js.coffee.haml . Is this possible? Simply saving my file with that extension does not work, I'm guessing Coffeebeans needs to be tweaked a bit to allow this, but I don't know what I would need to do.

This post suggested it would be possible: Chaining template handlers in Rails 3

Any suggestions on how to go about this?

Community
  • 1
  • 1
sooks
  • 688
  • 1
  • 8
  • 20
  • I would suggest continue using erb, because you can't have indentation inside plain text that .js is. With haml, unfortunately, the code does't look pretty :( – stef Jul 31 '13 at 17:08
  • Do you really need that? It would add significant overhead to view generations either way :) – Ian Sep 12 '13 at 20:38

1 Answers1

0

The question that you linked to had a second answer that linked to a blog post that was on posterous, which is now dead... but I found it on archive.org! The post also contains a gist with the code needed in an initializer so that you can name your files ending in js.coffee_haml and have them be processed.

In the interests of preventing future dead links, here is the code in the gist, but I didn't write it nor have I tested to see if it still works:

module Coffee
  module Rails
    class HamlTemplateHandler
      def self.haml_handler
        @@haml_handler ||= ActionView::Template.registered_template_handler(:haml)
      end

      def self.call(template)
        compiled_source = haml_handler.call(template)
        "CoffeeScript.compile(begin;#{compiled_source};end)"
      end
    end
  end
end

ActiveSupport.on_load(:action_view) do
  ActionView::Template.register_template_handler :coffee_haml, Coffee::Rails::HamlTemplateHandler
end

Also mentioned in the blog post is that haml doesn't allow nested plain text, so if you want to do something in coffeescript like this:

if xyz == 1
  do_this y
  do_that x

you have to wrap it in a :plain filter:

:plain
  if xyz == 1
    do_this y
    do_that x
carols10cents
  • 6,943
  • 7
  • 39
  • 56