Instance Variables in js.erb

Viewed 7483

From what I have read in several other questions, my instance variables defined in my controller should be accessible in my js.erb file. They aren't. Note: I'm not trying to render a partial - just access the variable's (string) content, which I will then apply to a div.

If not nil, my variables show up as true and crash on gsub if I use j (javascript escape) on them, in some cases - but that is a close to being able to differentiate between when they are nil and existing in the js.erb file. When they exist, I get an empty string returned in firebug-console on a console.log().

For example:

Controller Code

def myCntlMethod
   @myvar = "MyVarTest"
   respond_to do |format|
     format.js
   end
end

js.erb code:

console.log('<% @myvar %>');

Result in Firebug:

(an empty string)

Also tried

console.log('<% j @myvar %>');

same result in this case - crashes if I do an inspect or present? And ...

console.log('<% j myvar %>');

rails crashes and tells me the variable does not exist, as expected.

2 Answers
Related