我正在使用 Rails gon https://github.com/gazay/gon 从 Controller 获取数据,轻松插入 View 获得一个想法(只是一个例子):
def show
gon.alert = "this is an alert"
end
现在在我的 show.haml 中:
:javascript
alert(gon.alert)
现在我总是可以访问我之前在 Controller 操作中设置的 gon 值,但是如果您想从 application.coffee 访问 gon 值怎么办?
- 在哪里设置我可以在 application.coffee 中使用的 gon.current_user = 1?
最佳答案
如果您想设置一个可以从每个 Controller 操作访问的 gon 值,从而始终在 application.coffee 中可用,您可以在 ApplicationController
中设置一个 before_filter
>.
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :set_gon_values
private
def set_gon_values
gon.current_user = 1 # or whatever you want to set here
end
end
这将在所有 Controller 上的每个操作之前运行 set_gon_values
方法。这是可行的,因为您的所有 Controller 都继承自 ApplicationController
。
关于javascript - 如何将 gon 值传递给 application.coffee?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9957681/