How do I get escape_javascript and other helpers in my sprockets pre-processed js file (not a view)?

只愿长相守 提交于 2019-12-03 10:30:38

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" ) ) )%>"
};
balexand

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.

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 } %>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!