I have a Rails controller in which I am setting a instance variable -
@user_name = "Some Username"
In my .slim template I am using coffee engine to generate javascript and want to print out the user name from client-sie javascript code -
coffee: $(document).ready -> name = "#{@user_name}" alert name
But this is the javascript that is being generated??
$(document).ready(function() { var name; name = "" + this.my_name; alert(name); }
How do I access controller instance variables in my CoffeeScript code??
I am tagging this as haml since I am guessing haml will have the same issue when using CoffeeScript .
What's happening is that "#{@user_name}"
is being interpreted as CoffeeScript, not as Ruby code that's evaluated and injected into the CoffeeScript source. You're asking, "How do I inject a Ruby variable into my CoffeeScript source?"
The short answer is: Don't do this. The Rails team made an intentional decision not to support embedded CoffeeScript in templates in 3.1, because there's significant performance overhead to having to compile CoffeeScript on every request (as you'd have to do if you allowed arbitrary strings to be injected into the source).
My advice is to serve your Ruby variables separately as pure JavaScript, and then reference those variables from your CoffeeScript, e.g.:
javascript: user_name = "#{@user_name}"; coffee: $(document).ready -> name = user_name alert name
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With