简体   繁体   English

在application.js中运行root_path

[英]Rails root_path in application.js

How can I get my hands on the project's root_path in my application.js file? 如何在application.js文件中获取项目的root_path

I need it for a js plugin ( codemirror ) that needs to load other JS files. 我需要它来为需要加载其他JS文件的js插件( codemirror )。 It's all fine and dandy if I say "/javascripts/needed_file.js", but what if I deploy my project to "/custom". 如果我说“/javascripts/needed_file.js”,这一切都很好,但是如果我将项目部署到“/ custom”会怎么样。

The code needs to do its magic all over the project and I would like it to be UJS, so it needs to be in a static javascript file. 代码需要在整个项目中完成它的魔力,我希望它是UJS,所以它需要在一个静态的javascript文件中。

Any solutions/simple hacks? 任何解决方案/简单的黑客?

There's no beautiful solution. 没有漂亮的解决方案。 I'd try one of these approaches: 我会尝试以下方法之一:

  • Inspect window.location.pathname . 检查window.location.pathname Determine from this whether running from root or from a prefix url. 从中确定是从根运行还是从前缀url运行。

  • Add something like <script type="text/javascript" charset="utf-8">var ROOT_PATH = '<%= Rails.root_path %>';</script> somewhere to the top of your layout file. <script type="text/javascript" charset="utf-8">var ROOT_PATH = '<%= Rails.root_path %>';</script>到布局文件的顶部。

  • Use this quite hackish function (I suspect that it might break with some of the HTML5 script attributes): 使用这个非常hackish函数(我怀疑它可能会破坏一些HTML5脚本属性):

     function urlOfCurrentFile() { var scripts = document.getElementsByTagName("script"); return scripts[scripts.length - 1].src; } 

I have this in my header file. 我在头文件中有这个。

<script type="text/javascript">
  var BASE_URL = '<%= root_url %>';
</script>

Well, the best way I find is to leverage the power of JS to do so, like: 好吧,我找到的最好方法是利用JS的强大功能,例如:

window.location.origin # http://localhost:3000/

It's gonna give you the complete hostname, with http:// , and the port number. 它将为您提供完整的主机名, http://和端口号。 Like in case of running Rails server locally, it will give you: http://localhost:3000 就像在本地运行Rails服务器一样,它会给你: http://localhost:3000

window.location.hostname # localhost

It's just gonna give you the name of host, and nothing about port or HTTP. 它只会给你主机的名称,而不是端口或HTTP。 Incase of Rails server running locally, it will give you: localhost . 如果在本地运行Rails服务器,它会给你: localhost

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM