4

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.

0

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.