How to access instance variables in CoffeeScript engine inside a Slim template

Ruby on-RailsRuby on-Rails-3CoffeescriptHamlSlim Lang

Ruby on-Rails Problem Overview


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 .

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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

Solution 2 - Ruby on-Rails

I tend to avoid inline javascript at all costs.

A nice way to store variables in your HTML, to be used from your javascript, is to use the HTML5 data-attributes. This is ideal to keep your javascript unobtrusive.

Solution 3 - Ruby on-Rails

You could also use:

$(document).ready ->
  name = <%= JSON.generate @user_name %>
  alert name

This is because JSON is a subset of JavaScript.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkapsoView Question on Stackoverflow
Solution 1 - Ruby on-RailsTrevor BurnhamView Answer on Stackoverflow
Solution 2 - Ruby on-RailsnathanvdaView Answer on Stackoverflow
Solution 3 - Ruby on-Railsgene tsaiView Answer on Stackoverflow