【发布时间】: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 #<#<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 + ") %>");
引号被破坏了,所以它会导致 rails 出现错误:
syntax error, unexpected ';', expecting ')' ; _erbout.force_encoding(__ENCODING__) ^
这样我不知道如何处理。有什么办法吗?
【问题讨论】:
-
问题似乎是您试图从客户端执行服务器端方法
标签: javascript ruby-on-rails ruby coffeescript erb