[英]Using a Rails helper method within a javascript asset
有没有办法使用Rails助手方法,更具体地说,是javascript资产文件中的路径助手方法。 这个文件是foo.js.coffee.erb
$('#bar').val("<%= create_post_path %>")
如果我能从erubis那里得到,我会喜欢它
$('#bar').val("path/to/create")
您可以在erb模板中包含任何帮助器/模块/类:
<% 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
要使用网址助手,您必须包含特定应用程序的帮助程序。
它们可以在Rails.application.routes.url_helpers
中找到:
<% environment.context_class.instance_eval { include Rails.application.routes.url_helpers } %>
编辑:固定链接到移动的链轮回购但不确定这仍然有多年后的意义。
这也可以在初始化器中完成:
Sprockets::Context.send :include, MyHelper
在开发模式下,不会在每个请求上重新加载帮助程序。
您使用UrlHelpers的方法将一直有效,直到您需要找到post_path(...um...we don't know what post id we'll need at compile time...)
。 有一个ruby gem在JavaScript中重新实现了所有的Rails UrlHelpers: https : //github.com/railsware/js-routes
我不太确定,你为什么要这样做。
您可以阻止缓存javascript文件,因为它包含动态值
你会得到你的javascript / coffeescript和rails之间的耦合
如果可能,我会建议您通过在视图中提供目标路径来抽象问题,并在特定事件发生时从DOM元素中检索值。 就像Rails的'Unobtrusive Scripting Adapters'一样。 例如: https : //github.com/rails/jquery-ujs/blob/master/src/rails.js#L157-173
确实,我同意@eirc的答案(考虑到Sprockets文档)。 但我会考虑在rails启动时包含辅助模块。 按照
# config/initializers/sprockets.rb
Rails.application.assets.context_class.instance_eval do
include ActionView::Helpers
include Rails.application.routes.url_helpers
include MyModule
end
这是因为: https : //github.com/rails/sprockets-rails/blob/master/lib/sprockets/railtie.rb#L23
实际上,不确定这是否有帮助,但有一种方法可以定义自己的帮助程序,以便在rake precompile
期间使用
创建一个新的初始化程序并将其放入其中:
module Sprockets
module Helpers
module RailsHelper
def my_helper_method
...
end
end
end
end
然后你可以:
<%= my_helper_method %>
在你的.erb
资产中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.