Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

erb in coffee script with rails 3.1

I would like to use some erb in my .coffee files, like the following example

myLatlng: new google.maps.LatLng(<%[email protected] %>, <%[email protected] %>)

I renamed my locations.js.coffee to locations.erb.coffee

but I still get the following error

Error compiling asset application.js:
ExecJS::ProgramError: Error: Parse error on line 4: Unexpected 'COMPARE'
  (in /Users/denisjacquemin/Documents/code/projects/geolog/app/assets/javascripts/locations.erb.coffee)
Served asset /application.js - 500 Internal Server Error
like image 981
denisjacquemin Avatar asked Jun 28 '11 09:06

denisjacquemin


3 Answers

If you want erb in the .coffee files IN YOUR VIEW folder, leave your file named as yourfilename.js.coffee, and Rails will still process the ERB, oddly enough.

To make it work in Heroku, move coffee-rails out of the assets group in your Gemfile.

like image 181
Arcolye Avatar answered Nov 06 '22 07:11

Arcolye


You may have to rename your file to locations.coffee.erb so erb is processed before coffee :)

like image 13
Clément Avatar answered Nov 06 '22 06:11

Clément


Stick to the asset pipeline when possible in Rails 4, instead of using a js.erb view.

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 do
  gon.latitude = 0.1
  gon.longitude = 0.2
end

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

myLatlng: new google.maps.LatLng(gon.latitude, gon.longitude)

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.