【问题标题】:Coffesscript variables in ruby code piecesruby 代码片段中的咖啡脚本变量
【发布时间】:2017-10-18 18:44:48
【问题描述】:

我只是想从我的咖啡脚本中调用 rails helper。

问题是咖啡变量在 <%= ... %> 块中的 ruby​​ 代码片段中不可用。如果使用#{} 处理它们,则会以错误的方式转换为 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 #&lt;#&lt;Class:0x007f5e75ebd860&gt;:0x007f5e785d1410&gt;

好的,让我们把'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("&lt;%= input_type_hint(" + t + ") %&gt;"); 引号被破坏了,所以它会导致 rails 出现错误:

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

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

【问题讨论】:

  • 问题似乎是您试图从客户端执行服务器端方法

标签: javascript ruby-on-rails ruby coffeescript erb


【解决方案1】:

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

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

所以当你说input_type_hint(t)时,这是在服务器上运行的,但可怜的悲伤服务器不知道“t”是什么。

为了完成这项工作,您将在 coffeescript 中重新编码整个 input_type_hint 方法,以便它也可以在浏览器中运行! (然后它就不会出现在 &lt;%= =&gt; 东西中了。

顺便说一句,您可能想查看http://ruby-hyperloop.io,因为您无需使用coffeescript,而是随处编写ruby,而且您基本上不需要这种笨拙的ERB业务。

【讨论】:

    猜你喜欢
    • 2018-02-13
    • 2011-09-03
    • 2013-05-15
    • 1970-01-01
    • 1970-01-01
    • 2013-08-03
    • 2017-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多