在rails中生成javascript的完整url(类似于javascript_path,但是是url)
如何生成指向 javascript 文件的绝对链接。
我认为应该有类似下面的内容(不幸的是,它似乎不可用):
javascript_url 'main' # -> 'http://localhost:3000/javascripts/main.js'
而不是:
javascript_path 'main' # -> '/javascripts/main.js'
我需要绝对 URL,因为该 javascript 文件将在书签中使用。
另外我需要同样的 css 文件。
谢谢,
德米特里。
How is it possible to generate an absolute link to the javascript file.
I assume there should be something like the one below (which unfortunately does not seem to be available):
javascript_url 'main' # -> 'http://localhost:3000/javascripts/main.js'
instead of:
javascript_path 'main' # -> '/javascripts/main.js'
I need the absolute URL because that javascript file will be used in a bookmarklet.
Additionally I need the same for css file.
Thanks,
Dmitriy.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
也许您可以简单地将
javascript_path
与root_url
结合使用?例如:
root_url
由您的根路由自动生成。您还可以通过在环境的配置文件中设置
ActionController::Base.asset_host
将 Rails 帮助程序配置为使用特定的“基本路径”。请参阅文档了解更多信息。Maybe you could simply use
javascript_path
combined withroot_url
?For example:
root_url
is automatically generated by your root route.You could also configure the Rails helpers to use a specific "base path" by setting
ActionController::Base.asset_host
in your environment's configuration file. Read more in the documentation.Rails 4 现在在 ActionView::Helpers 中提供了 javascript 和 css 文件的绝对 URL: :AssetUrlHelper 模块通过资产管道。在您的情况下,具体来说它是 javascript_url 及其别名 url_to_javascript 以及样式表的相应方法。
结果正如您在问题中提到的那样:
虽然这个问题是很久以前提出的,但希望它能帮助人们将来寻求同一问题的答案。
Absolute URLs to javascript and css files are now available in Rails 4 in ActionView::Helpers::AssetUrlHelper module via Asset Pipeline. In your case specifically it's javascript_url and its alias url_to_javascript and corresponding methods for stylesheets.
And the result is exactly as you mentioned in your question:
Though the question was asked ages ago, hope it will help people seeking answer to the same question in future.
我写了这个小助手来做到这一点:
关键部分是 URI .merge 它将自动正确地将相对 javascript_path 与 root_url 合并。
I've written this little helper to do this:
The key part being URI.merge which will automatically, and correctly merge the relative javascript_path with root_url.