Rails 3.1/Sprockets:将控制器变量(或助手)注入 javascript 资产
我有一个操作,
def new
@test_var = 'i want this to show'
end
我想做的就是将其注入到该页面调用的 javascript 中。例如:
#app/assets/javascript/my_model.js.coffee.erb
$ ->
console.log('<%= @test_var %>')
我猜这不起作用,因为在访问控制器之前咖啡脚本/erb是编译的......所以,如果我想将控制器变量注入JavaScript文件(客户端 - 不通过ajax访问)在3.1中,我应该如何去做呢?
I have an action with
def new
@test_var = 'i want this to show'
end
All I want to do is inject that into the javascript called for that page. For example:
#app/assets/javascript/my_model.js.coffee.erb
$ ->
console.log('<%= @test_var %>')
I'm guessing this doesn't work because that the coffeescript/erb is compiled before the controller is accessed...so, if I wanted to inject controller variables into a JavaScript file (client side - NOT accessed via ajax) in 3.1, how should I go about doing it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为问题在于您对资产管道的思考完全错误......
资产是关键词。
它不是一个视图管道。其他哪些东西是资产?图像和css 文件,可以预处理然后按原样提供的东西。资产的 erb/预处理不会在每个页面加载/请求上发生,而是在启动/文件更改时发生,因此在生产中可以优化、缓存和静态提供资产。
您可能会找到一种使用实时编译来实现它的方法(请参阅 http://guides 的第 4.2 节。 rubyonrails.org/asset_pipeline.html),但正如文档所说:
糟糕的答案是“将 javascript 注入到您的视图中”,但将 javascript 与 Rails 控制器/视图解耦是一个好主意。
更好的答案是拥有一个包含所有控制器 JavaScript 的资产文件夹,并使用一些“我在哪个页面?” javascript 来确定是否运行代码。
以下是一些解释了各种方法的答案:
Rails 3.1 资产管道:如何加载特定于控制器的脚本?
使用 Rails 3.1,你把它放在哪里您的“页面特定”JavaScript 代码?
I believe the problem is that you're thinking about the asset pipeline all wrong...
asset being the operative word.
It's not a view pipeline. Other things which are assets? images & css files, things which can be preprocessed and then served as-is. The erb/preprocessing of your assets doesn't occur on each pageload/request, rather it occurs on startup/filechange so in production said assets can be optimised, cached and served statically.
You could probably figure out a way to achieve it using Live Compilation (see section 4.2 of http://guides.rubyonrails.org/asset_pipeline.html) but as the docs say:
The bad answer would be 'inject the javascript into your view', but decoupling your javascript from your rails controllers/views is a good idea.
A better answer would be to have an asset folder containing all of your controller javascripts, and use some "what page am I on?" javascript to determine whether to run the code or not.
Here's some answers that explain various approaches to this:
Rails 3.1 asset pipeline: how to load controller-specific scripts?
Using Rails 3.1, where do you put your "page specific" javascript code?