5

What would be the best way to pass values inside a .coffee script? Renaming the file to .erb breaks my app so what are the alternatives?

Rubytastic
  • 15,001
  • 18
  • 87
  • 175
  • possible duplicate of [Rails: access controller instance variable in CoffeeScript or JavaScript asset file](http://stackoverflow.com/questions/8513912/rails-access-controller-instance-variable-in-coffeescript-or-javascript-asset-f) – Ciro Santilli OurBigBook.com Oct 06 '14 at 12:16

2 Answers2

10

checkout this rails guide. this section : 2.3.3 JavaScript/CoffeeScript and ERB You can use rails code in .coffee-script file. It's built-in feature.

2nd Edit___

If the file is in assets pipeline then you need to add .erb extension at end of coffee file so that the rails tag works otherwise there is no need to add .erb extension if you moves the file in views folder rails tag works there.

Linh Dam
  • 2,033
  • 1
  • 19
  • 18
Muhammad Sannan Khalid
  • 3,127
  • 1
  • 22
  • 36
  • I think that the document you've linked to states that you need to change extension from .coffee to .coffee.erb – Kamil Szot Jul 13 '12 at 06:55
3

You can either (1) move the file into your app/views directory (so it won't be in the asset pipeline), or (2) pass the information via query string.

(1) app/views/users/script.js.coffee.erb

var username = <%= @user.name %>

(2) I'm using this function

<%= link_to "User", user_path(@user, :username => @user.name) %>
...
var username = getParameterByName('username')

Untested but this is the general idea.

Community
  • 1
  • 1
bricker
  • 8,911
  • 2
  • 44
  • 54