是否可以从资产文件中获取控制器和动作名称

是否可以从资产文件中获取控制器和动作名称

本文介绍了Rails:是否可以从资产文件中获取控制器和动作名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在资产管道中执行以下操作:

I want to do something like this in my asset pipeline:

application.js

application.js

//= require jquery
//= require jquery_ujs
//= require_tree ./includes
//= require global
<% if File.exists? "#{Rails.root}/assets/javascripts/#{params[:controller]}.js" %>
    //= require <%= params[:controller] %>
<% end %>
<% if File.exists? "#{Rails.root}/assets/javascripts/#{params[:controller]}/#{params[:action]}.js" %>
    //= require <%= params[:controller] %>/<%= params[:action] %>
<% end %>

现在这不起作用,因为资产文件无法访问params变量.现在有一种方法可以从资产中获取当前的控制器动作名称是什么?

Now this doesn't work because the assets files cannot access params variable. Now is there a way to grab what the current controller action names are from the asset?

还是为整个项目预编译了资产文件,以致于无法做到这一点?

Or is the asset file precompiled for the whole project, rending this impossible?

推荐答案

您也许可以通过一些Tom Foolery使其成为可能,但我强烈建议您这样做.

You may be able to make this possible through some Tom Foolery, but I would recommend highly against it.

我之所以这么说是因为您希望此js资源可缓存,并且确实如此,它确实需要是静态的.基于调用哪个控制器来定制资产将导致潜在的大量独特资源,所有这些资源都应分别标识,下载和缓存.注意到您已经包含了明显不变的资源(例如jQuery),并考虑了需要一遍又一遍地下载这些资源的可能性,我认为很明显,这种方法行之有效.

The reason I say so is because you want this js resource to be cacheable, and for that to be the case it really needs to be static. Customizing the asset based on what controller is being invoked is going to result in what is a potentially a lot of unique resources all of which should be identified, downloaded and cached separately. Noting that you have included what are obviously unchanging resources such as jQuery, and pondering the possibility that these would need to be downloaded over and over again, I think the point becomes clear this approach doesn't work to well.

如果您要基于控制器/操作自定义视图的初始化,我建议您将函数定义包含在要交付的静态js资产中,然后可以直接从页面调用.

If what you are trying to do is customize the initialization of a view based on the controller/action, I would recommend including function definitions in the static js asset you are delivering that you can then invoke directly from the page.

希望这会有所帮助.

这篇关于Rails:是否可以从资产文件中获取控制器和动作名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 01:50