简体   繁体   English

js.erb中的实例变量

[英]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. 根据我在其他几个问题中所读的内容,应该可以在js.erb文件中访问在控制器中定义的实例变量。 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. 注意:我不是要渲染部分内容-只是访问变量的(字符串)内容,然后将其应用于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. 如果不是nil,则在某些情况下,如果我在变量上使用j (javascript转义),我的变量将显示为true并在gsub上崩溃-但这几乎可以区分它们是nil还是存在于js.erb文件。 When they exist, I get an empty string returned in firebug-console on a console.log() . 当它们存在时,在console.log()上的firebug-console中返回an empty string

For example: 例如:

Controller Code 控制器代码

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

js.erb code: js.erb代码:

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

Result in Firebug: 结果导致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. rails崩溃,并告诉我该变量不存在,正如预期的那样。

The main reason of absence the evaluated text in result HTML is forgotten equal sign in the evaluation operator. 结果HTML中缺少评估文本的主要原因是在评估运算符中忘记了等号。 In order to ERB text processor inserted a value of a ruby code make sure that you have used the following form: 为了向ERB文本处理器插入一个ruby代码值,请确保您使用以下形式:

<%= @myvar %>

instead of: 代替:

<% @myvar %>

Second case form is need only ruby code execution inside the ERB template, not for a result insertion: 第二种情况是只需要在ERB模板中执行ruby代码,而不需要插入结果:

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

In the similar causes always at first check the equal sign in evaluation operators. 在类似的原因中,总是首先检查评估运算符中的等号。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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