Rails:自动包含动作/控制器特定的javascript文件吗? [英] Rails: Automatic inclusion of action/controller specific javascript files?
问题描述
我是Rails开发的初学者,从Cakephp搬来了.
I am a beginner at rails development and moved from cakephp.
在cakephp中,您可以在布局中执行一些操作,以自动包括任何名称与控制器或动作相同的javascript文件.
In cakephp there's something you can do in the layout to automatically include any javascript files that are named the same as either the controller or the action.
例如在www.website.com/post/add
For instance in www.website.com/post/add
post.js和post/add.js都将自动加载(如果存在).
both post.js and post/add.js will automatically be loaded if they exist.
有没有办法做到这一点?我试着做一个google,但不知道要搜索什么,也没发现太多.
Is there a way to do this in rails? I tried doing a google but didn't know what to search for and didn't turn up much.
(与CSS相同)
推荐答案
我不知道Rails中的这种功能, 但您可以在布局中简单地做到这一点:
I'm not aware of this kind of functionality in rails, but you can simply do this in a layout:
javascript_include_tag "#{controller.controller_name}"
javascript_include_tag "#{controller.action_name}"
它不会检查文件是否存在,因此您可以走得更远,创建应用程序帮助程序,然后在其中移动js的逻辑,包括并检查文件是否存在:
it will not check if the file exists, so you can go further and create application helper, and move there a logic of js including and checking if file exists:
def include_controller_js
javascript_include_tag "#{controller.controller_name}" if File.exists?("#{Rails.root}/public/javascripts/#{controller_name}.js")
end
但是自从Rails 3.1以来,有一个带有application.js清单文件的资产管道,所以也许您想了解更多有关它的信息.
But since rails 3.1 there is an asset pipeline with application.js manifest file, so maybe you would like to read more about it.
这篇关于Rails:自动包含动作/控制器特定的javascript文件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!