How can I get my hands on the project's root_path
in my application.js file?
I need it for a js plugin ( codemirror ) that needs to load other JS files. It's all fine and dandy if I say "/javascripts/needed_file.js", but what if I deploy my project to "/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.
Any solutions/simple hacks?
There's no beautiful solution. I'd try one of these approaches:
Inspect window.location.pathname
. Determine from this whether running from root or from a prefix 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.
Use this quite hackish function (I suspect that it might break with some of the HTML5 script attributes):
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:
window.location.origin # http://localhost:3000/
It's gonna give you the complete hostname, with http://
, and the port number. Like in case of running Rails server locally, it will give you: http://localhost:3000
window.location.hostname # localhost
It's just gonna give you the name of host, and nothing about port or HTTP. Incase of Rails server running locally, it will give you: localhost
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.