The right way to include page-specific JavaScript in Rails

后端 未结 5 783
青春惊慌失措
青春惊慌失措 2021-01-03 06:50

I want to include this, for example:

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

In one specific place in

5条回答
  •  感动是毒
    2021-01-03 07:39

    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) %>
      
     <% end %>
    

    Read more here about current_page?

    Or use request.fullpath to get current full path

    example :

     <% if request.fullpath == yourspecific_path %>
      
     <% end %>
    

    Read more here about request.fullpath

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

    cheers

提交回复
热议问题