Skip to content Skip to sidebar Skip to footer

How Do I Get Escape_javascript And Other Helpers In My Sprockets Pre-processed Js File (not A View)?

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

Solution 1:

You can include the rails JS helpers into your own class.

classHelperinclude ActionView::Helpers::JavaScriptHelper

  def self.escape_js( text )
    @instance||= self.new
    return@instance.escape_javascript( text )
  endend

Then use it in your ERB file:

obj = {
 name: "test",
 tag: "<%= Helper.escape_js( image_tag( "logo.png" ) ) )%>"
};

Solution 2:

Call it through ActionController::Base.helpers like this:

// file.js.erbvar 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.

Solution 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 } %>

Post a Comment for "How Do I Get Escape_javascript And Other Helpers In My Sprockets Pre-processed Js File (not A View)?"