问题描述
如果我在 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 资产管道:如何加载特定于控制器的脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!