在 javascript 资产中使用 Rails 辅助方法 [英] Using a Rails helper method within a javascript asset

查看:27
本文介绍了在 javascript 资产中使用 Rails 辅助方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以使用 Rails 辅助方法,更具体地说,是 javascript 资产文件中的路径辅助方法.这个文件 foo.js.coffee.erb

Is there any way to use a Rails helper method, more specifically, a path helper method within a javascript asset file. This file foo.js.coffee.erb

$('#bar').val("<%= create_post_path %>")

如果我能从 erubis 得到我会喜欢它

I would love it if I could get from erubis

$('#bar').val("path/to/create")

推荐答案

您可以通过以下方式在 erb 模板中包含任何帮助程序/模块/类:

You can include any helper/module/class in an erb template with:

<% environment.context_class.instance_eval { include MyHelper } %>

参见:https://github.com/rails/链轮/blob/master/lib/sprockets/environment.rbhttps://github.com/rails/sprockets/blob/master/lib/sprockets/context.rb

要使用 url 帮助程序,您必须包含特定应用程序的帮助程序.

To use the url helpers you have to include your specific applications' helpers.

它们可以在 Rails.application.routes.url_helpers 获得,所以:

They are available at Rails.application.routes.url_helpers so:

<% environment.context_class.instance_eval { include Rails.application.routes.url_helpers } %>

修复了移动链轮存储库的链接,但不确定这么多年后这仍然有意义.

Fixed links to moved sprockets repo but not really sure this still makes sense so many years later.

这篇关于在 javascript 资产中使用 Rails 辅助方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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