8

In my rails 3.1.3 app, I'd like to insert some ERB code in my javascript file but it's not being parsed for some reason:

# app/assets/javascripts/application.js
//= require_tree ./shared

# app/assets/javascripts/shared/shared.js.erb
MM.loading = '<img src="<%= asset_path("icons/ajax-loader.gif") >">';

Gets rendered like this in /application.js:

MM.loading = '<img src=" asset_path("icons/ajax-loader.gif") >">';

I can't see any extra steps in the rails guides - is there something I'm missing? Btw I'm using haml for the view files, and also tried the above with .js.haml, enclosing in #{...}.

Zubin
  • 9,422
  • 7
  • 48
  • 52

3 Answers3

10

You have a syntax error in your code. This:

MM.loading = '<img src="<%= asset_path("icons/ajax-loader.gif") >">';

should be this:

MM.loading = '<img src="<%= asset_path("icons/ajax-loader.gif") %>">';

You were missing the closing erb tag for the helper block of code.

Richard Hulse
  • 10,383
  • 2
  • 33
  • 37
0

In Rails 4, instead of using a js.erb view, I recommend that you stick to the asset pipeline whenever possible, and pass variables to the Js using gon or some other technique discussed at: Ruby on Rails - Send JavaScript variable from controller to external Javascript asset file

With gon:

app/views/layouts/application.html.erb:

<head>
  <meta charset="utf-8"/>
  <%= include_gon %>

app/controllers/application_controller.rb:

before_filter { gon.path = asset_path('icons/ajax-loader.gif') }

app/assets/javascripts/shared.js.coffee:

MM.loading = '<img src="' + gon.path + '">';

This method is faster because file is precompiled only once at startup, gets served by the server instead of through Rails, and on the same HTTP request as the rest of the Js.

The particular use case of passing an asset URL to Javascript has been asked at: URL of images in JavaScript code using Rails 3.1 asset pipeline?

Community
  • 1
  • 1
Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
-2

Add a .erb extension to your application.js and it should work.

The content of required files gets included first, then processed according to the extensions on the manifest.

Richard Hulse
  • 10,383
  • 2
  • 33
  • 37
  • Good idea, but didn't work for me. Tried `console.log("1 + 1 = <%= puts 1+1 %>");` in `shared.js.erb` after appending `.erb` to manifest filename. – Zubin Jan 23 '12 at 03:18
  • This was not required. After fixing the brackets it worked without appending .erb on the manifest filename. – Zubin Jan 23 '12 at 04:54