Ok, I realise this question has been asked many times but the answers never seems to address the issue/question I have with this.
I have a js file that I would like to include on specific pages only. There are many responses that suggest that I put files into folders and then in the manifest file reference only those folders - for example this Railscast (at about 06:20) talks about this.
However, I only have one application layout file (and I guess this could be the area I'm lacking in) - therefore this file points to the application.js manifest and therefore I can't see how I can include things conditionally.
It's a bit like this resource too - http://railsapps.github.io/rails-javascript-include-external.html - scroll down to the page-specific scripts sub heading and it repeats what the Railscast suggests. But nothing is mentioned of multiple application layout files.
If anyone can help me clarify what to do in this situation I would be most grateful.
I should perhaps point out that I'm using Rails 4.
The directory structure for JavaScript has changed to the app/javascript/packs/ folder. In that folder you will find the application. js file, which is just like the application. css file.
javascript_include_tag(*sources) Link. Returns an HTML script tag for each of the sources provided. Sources may be paths to JavaScript files. Relative paths are assumed to be relative to public/javascripts , full paths are assumed to be relative to the document root.
The javascript_pack_tag takes care of making sure that it references compiled assets properly in development mode as well as in production mode similar to the assets pipeline.
You can use content_for in your views to "inject" content into the layout when said view is to be rendered. See: using-the-content-for-method
You'd need to do a few things to make this happen:
Add the placeholder to yield the content in the layout. ex.
<%= yield :js %>
Add the block (to be yielded) to your view. ex:
<%= content_for :js do %>
<%= javascript_include_tag "my_script" %>
<% end %>
If you are using the asset pipeline in production and you want to reference a particular asset like a "my_script.js", in your production.rb or relevant environment config.you will need to precompile it using:
config.assets.precompile=["my_script.js"]
In application.html.erb
, use this to add controller specific javascript instead of application specific javascript. Make sure you remove require_tree
.
<%= javascript_include_tag params[:controller] %>
Read more on this topic on Rails Guide.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With