如何在haml模板的coffeescript中使用ruby代码中的局部变量或实例变量 [英] How to use local or instance variable in ruby code in coffeescript in haml template

查看:20
本文介绍了如何在haml模板的coffeescript中使用ruby代码中的局部变量或实例变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Rails 的新手,在尝试在 haml 模板中的 coffeescript 中使用 ruby​​ 辅助方法中的变量时遇到了复杂的问题.

I'm newer of rails and facing complex issue trying to use variable in ruby helper method in coffeescript in haml template.

这是我在haml中的代码

Here is my code in haml

:coffee
  $('input#field').blur ->
    input = $('input#field').val()
    #{ ruby_method( input )}

ruby_helper.rb

ruby_helper.rb

def ruby_method (arg)
    if arg
        @model = Model.new(arg)
    end
end

这会导致如下错误

未定义的局部变量或方法

undefined local variable or method

也试过实例变量

:coffee
  $('input#field').blur ->
    @input = $('input#field').val()
    #{ ruby_method( @input )}

这不能传递给辅助方法.

This can not pass it to helper method.

如何在 ruby​​ 辅助方法中获取 javascript 变量?

How can I get javascript variable in ruby helper method?

提前致谢!

推荐答案

Coffee Script 和 Rails 引擎的关系?

rails和coffee脚本之间没有关系,rails中的任何内容都不能在coffee脚本中访问.

There is no relation between rails and coffee script and nothing in rails can be accessed in coffee script.

那我该怎么办?

只需在您的视图文件夹中创建 def.js.erb 文件并编写您的 javascript 代码.在此文件中,您可以访问方法中的所有实例变量.

Just create def.js.erb file in your view folder and write your javascript code. in this file you can access all instance variable in method.

它是如何调用 method.js.erb 的?

使用这个:

respond_to do |format|
  format.js
end

这将调用 method.js.erb 文件而不是 method.html.erb 文件.

this will call method.js.erb file instead of method.html.erb file.

希望对您有所帮助

这篇关于如何在haml模板的coffeescript中使用ruby代码中的局部变量或实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆