问题
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
回答1:
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" ) ) )%>"
};
回答2:
Call it through ActionController::Base.helpers like this:
// file.js.erb
var x = "<%= ActionController::Base.helpers.j image_tag('logo.png') %>";
Note that j is an alias for escape_javascript, so you can use the long name if you prefer.
回答3:
You may also either include JavaScriptHelper
directly into the Sprockets Context
class (the class that runs your template):
<% environment.context_class.instance_eval { include ActionView::Helpers::JavaScriptHelper } %>
Or even define your helper somewhere else and include that in the template (so as to be able and reuse the helper)
<% environment.context_class.instance_eval { include MyHelper } %>
来源:https://stackoverflow.com/questions/6838550/how-do-i-get-escape-javascript-and-other-helpers-in-my-sprockets-pre-processed-j