简体   繁体   中英

How do assets work in Rails?

I want to use jQuery/Bootstrap/other 3rd party js in my Rails app but I cannot understand how Rails work in terms of how it references those scripts.

In my Gem file I have:

gem 'jquery-rails',   '4.0.3'
gem 'bootstrap-sass', '3.2.0.0'
gem 'sass-rails',     '5.0.2'

and I see that Rails includes the following in assets/application.js

//= require jquery
//= require jquery_ujs

Does that mean that Rails will include jQuery for every screen that my App has?

What if I want to use a 3rd party only for some screens, not every screen . How can I accomplish that?

And I couldn't find jQuery.min.js anywhere in my Rails project. Where it is located ?. I've been searching in the following: app/assets/javascripts , vendor/assets/javascripts , lib/assets but no jQuery/jQuery UI script.

  1. Yes it will include it on every single screen rendered using the default layout ( app/views/layouts/application.html.erb )

  2. The jquery/sass/bootstrap css/js files live in the gems directory (somewhere deeply inside your ruby installation directory). So they are outside of your project, and sprockets extracts them from that external directory.

  3. To avoid including those files on every single page you just need to create an another layout which will not reference the application.js file.

To include difference scripts using on different pages with the same layout you can use the content_for helper, there is quiet a lot of things to change, so:

app/views/layouts/application.html

# remove this
<% javascript_include_tag 'application', 'data-turbolinks-track' => true %>

# and add this
<%= yield :scripts %>

Next in all your views you can add something like this (anywhere in the file):

<% content_for :scripts do %>
   <%= javascript_include_tag 'application' %>
<% end %>

That specific example will just include the application.js with dependencies on some pages, and will include nothing on other pages. Generally you can create more than one manifest file (many application.js-like files.) But if you are not really comfortable with sprockets it will be much simpler for you to just put the regular js files into the public directory and then include them using something like:

<% content_for :scripts do %>
  <script src="javascripts/jquery.js" ></script>
  <script src="javascripts/pagination.js" ></script>
<% end %>

And the javascripts/jquery.js should be available in your public directory.

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