Rails 3.1/Sprockets:将控制器变量(或助手)注入 javascript 资产

发布于 2024-12-06 05:29:52 字数 356 浏览 1 评论 0原文

我有一个操作,

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

半枫 2024-12-13 05:29:52

我认为问题在于您对资产管道的思考完全错误......
资产是关键词。

它不是一个视图管道。其他哪些东西是资产?图像和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:

This mode uses more memory and is lower performance than the default. It is not recommended.

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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文