Rails 3.1 Asset Pipeline:如何加载特定于控制器的脚本? [英] Rails 3.1 asset pipeline: how to load controller-specific scripts?
问题描述
如果我在Rails 3.1中生成一个新的控制器,则带有控制器名称的javascript文件也会自动添加.首先,我认为只有在调用相关的控制器时,才会使用此javascript文件.
If I generate a new controller in Rails 3.1, also a javascript file with the name of the controller will added automatically. Firstly, I thought this javascript file will used only, when the related controller is called.
默认情况下,在application.js
文件中有一条指令//= require_tree .
,其中包括树上的每个javascript文件.
By default there is the instruction //= require_tree .
in the application.js
-file, that include every javascript file on it's tree.
如何仅加载控制器特定的脚本?
How could I load only the controller specific script?
推荐答案
仅加载必要的name_of_the_js_file.js文件:
To load only the necessary name_of_the_js_file.js file:
-
从
application.js
将您的js文件(要在加载特定页面时加载的文件)保留在资产管道中
keep your js file (that you want to load when a specific page is loaded) in the asset pipeline
在application_helper.rb
def javascript(*files)
content_for(:head) { javascript_include_tag(*files) }
end
将您的布局屈服:
yield into your layout:
<%= yield(:head) %>
将此添加到您的视图文件中:
add this in your view file:
<% javascript 'name_of_the_js_file' %>
那应该没事
这篇关于Rails 3.1 Asset Pipeline:如何加载特定于控制器的脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!