[英]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.我想在我的代码中保持 DRY,所以我想在它匹配控制器或/和方法并且.js
存在时自动加载我的 javascripts 文件。 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.所以现在当我添加javascripts/my_controller/my_method.js
它会自动加载它,这很好。
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.遗憾的是,我必须添加另一行来预编译资产,否则会引发错误(表示我必须预编译我的.js
文件),但我没有找到任何解决方法。
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 .
注意:我已经尝试使用require_tree .
which was just loading all the files on every page and was not working in my case.这只是加载每个页面上的所有文件,在我的情况下不起作用。
您可以使用通配符来预编译视图中包含的所有 JS 文件:
config.assets.precompile << '*.js'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.