资产管道中的路由助手 [英] Route helpers in asset pipeline

查看:23
本文介绍了资产管道中的路由助手的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Rails 3.1.0.rc4,我试图访问 javascript 文件(在本例中为 event.js.erb)中的路由帮助程序,但当时似乎没有加载它们.当请求合并的/assets/application.js 文件时,我得到:

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:

throw Error("NameError: undefined local variable or method `events_path' for #<#<Class:0x00000001580010>:0x00000003191510>
  (in /<...>/app/assets/javascripts/event.js.erb)")

知道如何访问那里的路线助手吗?

Any idea how to access the route helper in there?

推荐答案

更新:现在有一个 gem 可以为您执行此操作:js 路由

UPDATE: Now there is a gem that does this for you: js-routes

问题在于 Sprockets 正在 Rails 应用程序上下文之外评估 ERB,而您期望的大部分内容都不存在.

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 上下文添加内容:

You can add things to your Sprockets context like so:

Rails.application.assets.context_class.class_eval do
  include Rails.application.routes.url_helpers
end

这一切都很好,但是让需要 id 的助手工作有点棘手.我将使用一种称为 URI 模板的技术:

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:

var event_path = "<%= CGI.unescape event_path('{event_id}') %>";

返回 /events/{event_id} 您可以使用像 { event_id: 1 } 这样的对象将其渲染到 url 中.请参阅 SugarJS 的 String#assign 方法作为其示例实现.你也可以像我一样自己动手

which returns /events/{event_id} which you could render into a url using an object like { event_id: 1 }. See SugarJS's String#assign method as example implementation of this. You could also roll your own like I did.

这篇关于资产管道中的路由助手的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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