ohad c
ohad c

Reputation: 5

Use JS var in ruby line inside js file

I'm trying to use js var inside ruby line (which all are inside a js.erb file):

my_file.js.erb:

var x = 3;
var credit = "<%= CreditsController.some_method(x) %>";

I know how to replace text in js var, but don't know how to do it before running the ruby part <%= %>

Thanks!

Upvotes: 0

Views: 68

Answers (2)

thaleshcv
thaleshcv

Reputation: 752

what you can do is something like:

in your CreditsController:

def some_method
  @credit = 0
end

and in your some_method.js.erb:

var credit = "<%= @credit %>";

Upvotes: 0

sz23
sz23

Reputation: 36

That's not possible because your file my_file.js.erb will be processed into my_file.js on the server side replacing every ruby code with their outputs it provides. Finally, your navigator will execute the javascript.

As Stefan said, you could try fetching that value by an ajax call, or trying to implement that function in the javascript, if it is possible.

Upvotes: 2

Related Questions