I'm using Rails 3.1 and the sprockets stuff.
I want to use ERB to pre-process a js file that will then be included using javascript_include_tag. It is generated from code, and so I'm pre-processing it with ERB, but I can't get to the helpers like escape_javascript from ActionView::Helpers::JavaScriptHelper
Say my file is called dynamic.js.erb, and it contains
obj = {
name: "test",
tag: "<%= escape_javascript( image_tag( "logo.png" ) )%>"
};
How do I stop it from producing the error:
throw Error("NoMethodError: undefined method `escape_javascript' for #<#<Class:0x1067da940>:0x116b2be18>
(in /Users/me/site/app/assets/javascripts/dynamic.js.erb)")
When I hit my local server and ask for /assets/dynamic.js
You can include the rails JS helpers into your own class.
class Helper
include ActionView::Helpers::JavaScriptHelper
def self.escape_js( text )
@instance ||= self.new
return @instance.escape_javascript( text )
end
end
Then use it in your ERB file:
obj = {
name: "test",
tag: "<%= Helper.escape_js( image_tag( "logo.png" ) ) )%>"
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With