简体   繁体   中英

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM