12

How to include Rails view helpers to be accesible by assets pipeline execution context?

An example use case would be to generate the markup for a form, using form_tag helper method, and make it available to a Javascript template (like handlebars, jst, etc.).

I use handlebar_assets gem, but this should apply to any erb or haml template too.

brutuscat
  • 3,139
  • 2
  • 28
  • 33

2 Answers2

29

Create a inititializer and include the helpers in the context of the assets like this:

Rails.application.assets.context_class.class_eval do
  include ActionView::Helpers
  include MyAppHelper
  include Rails.application.routes.url_helpers
end

Taken from this sprockets issue

brutuscat
  • 3,139
  • 2
  • 28
  • 33
  • This also worked for me when I wanted to render a custom ERB to string with `template = ERB.new(html) template.result(binding)`. Without this I wasn't able to use concat and other simple helpers. – benathon Jun 04 '13 at 09:35
  • @brutuscat, can you clarify where you would put this code? Thanks – jackerman09 Nov 08 '13 at 02:17
  • 2
    @jackerman09 no problem: "Create a inititializer", see more here http://guides.rubyonrails.org/configuring.html#using-initializer-files – brutuscat Nov 08 '13 at 22:10
  • reference: https://github.com/rails/sprockets-rails/issues/307#issuecomment-170707886 – bhaibel Jan 11 '16 at 23:04
15

The above answer is now out of date. As of sprockets-rails 3, the appropriate interface is a configure block, like so:

Rails.application.config.assets.configure do |env|
  env.context_class.class_eval do
    # include SomeHelper
  end
end

This configure block should still be placed in an initializer.

reference: https://github.com/rails/sprockets-rails/issues/307#issuecomment-170707886

bhaibel
  • 393
  • 2
  • 6