简体   繁体   中英

How to write the content of external .js files in a js.haml file (Ruby on Rails)

I'm using Ruby on Rails framework and I love it.

Until now I was using the show.html.haml for my views and everything worked fine. We wanted to add another option of supporting a GET request which consists the post-fix .js . For this purpose we added to the controller another parallel view named show.js.haml . The "magic" of Rails knows to route .html post-fix requests to the first and .js post-fix requests to the latter.

The problem is when a request gets routed to the show.js.haml view, I can't find a way to write the content of external .js files. All I get is the text itself (ie <script src="myscripts.js" type="text/javascript"></script> ) but not the actual content of the file.

I've found a solution, which surely isn't optimal (performance, robustness etc): downloading the file to the server and use the following function:

!= File.open(Rails.root.join('public' , 'js',  'jquery-1.11.2.min.js'), 'rb').read

This is the only way I found to actually write the content of a .js file.

There must be a Ruby's elegant way to write the content of external .js files into a .js.haml file.

Any help would be appreciated here. Thanks!

I'm not sure why you need this and which case this is a good idea for, but you can try this (untested):

# show.js.haml

// some javascript
= render file: Rails.root.join('public' , 'js',  'jquery-1.11.2.min.js')
// or
"#{render file: Rails.root.join('public' , 'js',  'jquery-1.11.2.min.js')}"

Of course this will only work for local resources accessible, but hey, that's what <script src= is for.

EDIT

In case of needing to store the contents of the file in a variable as a string, you can use capture . For remote files you can use open-uri , which is part of Ruby's stdlib.

# show.js.haml
- content = capture do
- render file: Rails.root.join('public' , 'js',  'jquery-1.11.2.min.js')

# for remote files
- content = open('http://url.to/file.js').read

You can print the content later on:

= content

我认为您需要的是Rails资产管道http://guides.rubyonrails.org/asset_pipeline.html

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.

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