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

查看:146
本文介绍了在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模板中包含任何帮助器/模块/类with:

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

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

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

要使用网址助手,您必须包含特定应用程序的帮助程序。

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

它们位于 Rails.application.routes.url_helpers 所以:

<% 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天全站免登陆