繁体   English   中英

红宝石代码段中的Coffesscript变量

[英]Coffesscript variables in ruby code pieces

我只是想从我的coffeescript中调用Rails助手。

问题在于,在<%= ... %>块中的红宝石代码段中,咖啡变量不可用。 如果使用#{}处理它们,则会以错误的方式将其转换为JS。 所以,让我举例说明。 这是一个.js.coffee.erb文件:

<% environment.context_class.instance_eval { include InputsHelper } %>
$('#input_input_type').change ->
  t = $('#input_input_type').val()
  $('.input_address .help-block').html('<%= input_type_hint(t) %>')

这段代码会产生这样的错误: undefined local variable or method 't' for #<#<Class:0x007f5e75ebd860>:0x007f5e785d1410>

好的,让我们在#{}输入't':

<% environment.context_class.instance_eval { include InputsHelper } %>
$('#input_input_type').change ->
  t = $('#input_input_type').val()
  $('.input_address .help-block').html("<%= input_type_hint(#{t}) %>")

这会以错误的方式转换为JS。 最后一个字符串如下所示: $('.input_address .help-block').html("<%= input_type_hint(" + t + ") %>"); 引号已损坏,因此导致滑轨因错误而掉落:

syntax error, unexpected ';', expecting ')' ; _erbout.force_encoding(__ENCODING__) ^

这样,我不知道该如何管理。 有什么办法吗?

没有简单的方法可以做到这一点。

问题是,咖啡脚本在浏览器中执行,但是<%= ... %>的内容在服务器构建咖啡脚本时在服务器上执行。

因此,当您说input_type_hint(t)它正在服务器上运行,但是性能较差的服务器不知道“ t”是什么。

为了使这项工作有效,您将需要在coffeescript中重新编码整个input_type_hint方法,以便它也可以在浏览器中运行! (然后它将不会出现在<%= =>

顺便说一句,您可能要签出http://ruby-hyperloop.io ,而不是使用coffeescript而是在各处写红宝石,并且您基本上不需要笨拙的ERB业务。

暂无
暂无

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

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