Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The right way to include page-specific JavaScript in Rails

I want to include this, for example:

jQuery(document).ready(function($) {
    $('#my-modal').modal(options)
});

In one specific place in a rails app. In my case the file is called views/modals/mymodal.html.erb. There and only there.

I can't figure out how to do that without getting it on all pages as would happen if I put it in assets.

like image 364
pitosalas Avatar asked Dec 11 '22 06:12

pitosalas


1 Answers

These are some useful tricks

#1 with file js

  • Create file your.js for your javascript
  • call file your.js on specific your layout
  • remove //= require_tree . on application.js
  • add your.js to asset percompile on config/application.rb : config.assets.precompile += %w( your.js )

#2 put into specific file non layout (not recommended)

put your js script with javascript tag on mymodal.html.erb


#3 use if..else..

put your js script into layout/yourlayout.html.erb and use if.. else.. logic.

example :

 <% if current_page?(yourspecific_path) %>
  <script language="text/javascript">
   your javascript here ..
  </script>
 <% end %>

Read more here about current_page?

Or use request.fullpath to get current full path

example :

 <% if request.fullpath == yourspecific_path %>
  <script language="text/javascript">
   your javascript here ..
  </script>
 <% end %>

Read more here about request.fullpath

Also you can combine #1 and #3 if you want script put into file .js

cheers

like image 173
rails_id Avatar answered Jan 04 '23 23:01

rails_id