Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instance Variables in js.erb

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.

like image 703
JosephK Avatar asked Oct 18 '25 18:10

JosephK


1 Answers

The main reason of absence the evaluated text in result HTML is forgotten equal sign in the evaluation operator. In order to ERB text processor inserted a value of a ruby code make sure that you have used the following form:

<%= @myvar %>

instead of:

<% @myvar %>

Second case form is need only ruby code execution inside the ERB template, not for a result insertion:

<% @myvars.each do| myvar | -%>
  <p></p>
<% end %>

In the similar causes always at first check the equal sign in evaluation operators.

like image 136
Малъ Скрылевъ Avatar answered Oct 20 '25 09:10

Малъ Скрылевъ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!