在资产管道中路由助手

编程入门 行业动态 更新时间:2024-10-27 03:33:57
本文介绍了在资产管道中路由助手的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

使用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>\n (in /<...>/app/assets/javascripts/event.js.erb)")

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

Any idea how to access the route helper in there?

推荐答案

更新:现在有一个宝石可以帮到你: js -routes

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} 这样的对象将其呈现到网址中。请参阅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.

更多推荐

在资产管道中路由助手

本文发布于:2023-07-08 01:06:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1070182.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:路由   道中   助手   资产

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!