简体   繁体   中英

How to put JavaScripts anywhere besides /public/javascripts in Rails 3?

I have a Rails 3 view (for my_controller#show) which has a lot of JavaScript.

I'd like to move that JavaScript to a separate my_show.js file and then include that file using Rails' javascript_include_tag method. This works if I put my_show.js in the /public/javascripts directory. But I'd prefer to put the file in the same directory with the view with which it's associated.

Is it possible to configure rails such that I can use javascript_include_tag to include files outside /public/javascripts ?

My solution right now is to make a partial called _my_show.html.haml . In this file I put my JavaScript code. Then I include the file with render .

I'm wondering if there's a preferred Rails 3 way to do what I want.

You could consider creating a route for the js file.

get '/my_controller/show_js.js' => 'my_controller#show_js'

And put your js content in views/my_controller/show_js.js.erb

Now, you should be able to include your js file by:

javascript_include_tag "/my_controller/show_js.js"

The upcoming Rails 3.1 includes the Sprockets gem to provide an Asset Pipeline feature that offers more flexibility in placement of JavaScript and other assets.

One can also use Sprockets independently of Rails 3.1.

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