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

前端 未结 29 2104
一生所求
一生所求 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:24

    I combined some answers into:

    Application helper:

    module ApplicationHelper
      def js_page_specific_include
        page_specific_js = params[:controller] + '_' + params[:action]
        if Rails.application.assets.find_asset(page_specific_js).nil?
          javascript_include_tag 'application', 'data-turbolinks-track' => true
        else
          javascript_include_tag 'application', page_specific_js, 'data-turbolinks-track' => true
        end
      end
    end
    

    layouts/application.html.haml:

     
    %html{lang: 'uk'}
      %head   
        = stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true
       bla-bla-bla
        = js_page_specific_include   
       bla-bla-bla  
    

提交回复
热议问题