javascript 资产管道中的路由助手
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6725629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Route helpers in asset pipeline
提问by tbuehlmann
using Rails 3.1.0.rc4, I'm trying to access a route helper in a javascript file (event.js.erb in this case) and it seems like they are not loaded at that moment. When requesting the merged /assets/application.js file, I get:
使用 Rails 3.1.0.rc4,我试图访问一个 javascript 文件(在这种情况下为 event.js.erb)中的路由助手,但似乎当时没有加载它们。当请求合并的 /assets/application.js 文件时,我得到:
throw Error("NameError: undefined local variable or method `events_path' for #<#<Class:0x00000001580010>:0x00000003191510>\n (in /<...>/app/assets/javascripts/event.js.erb)")
Any idea how to access the route helper in there?
知道如何访问那里的路线助手吗?
回答by Adam Lassek
UPDATE: Now there is a gem that does this for you: js-routes
更新:现在有一个 gem 可以为您执行此操作:js-routes
The problem is that Sprockets is evaluating the ERB outside of the context of your Rails app, and most of the stuff you're expecting isn't there.
问题是 Sprockets 正在 Rails 应用程序上下文之外评估 ERB,而您期望的大部分内容都不存在。
You can add things to your Sprockets context like so:
您可以将内容添加到您的 Sprockets 上下文中,如下所示:
Rails.application.assets.context_class.class_eval do
include Rails.application.routes.url_helpers
end
That's all well and good, but getting the helpers that require an id to work is a little trickier. I'm going to use a technique called a URI Template:
这一切都很好,但是让需要 id 的助手工作有点棘手。我将使用一种称为URI 模板的技术:
var event_path = "<%= CGI.unescape event_path('{event_id}') %>";
which returns /events/{event_id}
which you could render into a url using an object like { event_id: 1 }
. See SugarJS's String#assignmethod as example implementation of this. You could also roll your ownlike I did.
它返回/events/{event_id}
您可以使用像{ event_id: 1 }
. 参见 SugarJS 的String#assign方法作为它的示例实现。你也可以像我一样滚动你自己的。
回答by Peter Hawkins
You could move the file to views where it has access to the proper context, then pull it down to the client from a JS source tag. Referring to MyRailsApp::Application.routes.url_helpers may not be the best if you are writing an engine.
您可以将文件移动到可以访问正确上下文的视图中,然后将其从 JS 源标记拉到客户端。如果您正在编写引擎,参考 MyRailsApp::Application.routes.url_helpers 可能不是最好的。