Using Rails 3.1, where do you put your “page specific” JavaScript code?

前端 未结 29 2084
一生所求
一生所求 2020-11-22 11:08

To my understanding, all of your JavaScript gets merged into 1 file. Rails does this by default when it adds //= require_tree . to the bottom of your appl

29条回答
  •  春和景丽
    2020-11-22 11:36

    You can add this line in your layout file (e.g. application.html.erb) to automatically load the controller specific javascript file (the one that was created when you generated the controller):

    <%= javascript_include_tag params[:controller] %>
    

    You also could add a line to automatically load a script file in a per-action basis.

    <%= javascript_include_tag params[:controller] + "/" + params[:action] %>
    

    Just put your page scripts into a subdirectoriy named after the controller name. In these files you could include other scripts using =require. It would be nice to create a helper to include the file only if it exists, to avoid a 404 fail in the browser.

提交回复
热议问题