简体   繁体   中英

Rails Assets Pipeline load JavaScript from controllers and methods

I want to stay DRY in my code so I want to auto-load my javascripts file when it matches a controller or/and a method and the .js exists. I added this to my layout

= javascript_include_tag params[:controller] if ::Rails.application.assets.find_asset("#{params[:controller]}.js")
= javascript_include_tag "#{params[:controller]}/#{params[:action]}" if ::Rails.application.assets.find_asset("#{params[:controller]}/#{params[:action]}.js")

So now when I add javascripts/my_controller/my_method.js it automatically loads it, which's nice.

Sadly I must add another line to precompile the asset otherwise an error is thrown (which says I must precompile my .js file) and I didn't find any way around this.

Rails.application.config.assets.precompile += %w( orders/checkout.js )

Does anyone has a solution to avoid tu add manually elements in this configuration ?

NOTE : I already tried to use require_tree . which was just loading all the files on every page and was not working in my case.

您可以使用通配符来预编译视图中包含的所有 JS 文件:

config.assets.precompile << '*.js'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM