在rails中为每个控制器加载Javascript [英] Loading Javascript per controller in rails
问题描述
我调查了类似的线程,但我无法捕捉到。下面是我的application.js文件。
I looked into similar threads, but i am not able to catch. Below is my application.js file.
//= require jquery
//= require jquery_ujs
//= require bootstrap
//= require vendor
//= require_tree .
我的资产管道目录结构如下所示。
I have a directory structure of my assets pipeline as below.
--javascripts
-misc // directory
helper.js
session.js
app.js
application.js
home.js
我如何为所有人加载misc目录 HomeController
的pages和home.js以及 SessionController
的session.js。我不想让不需要的JS在每个地方加载。
How would i load the misc directory for all pages and home.js for HomeController
and session.js for SessionController
. I don't want unwanted JS to get loaded every where.
推荐答案
正如 Dave所指出的那样/ code>您可以将建议的解决方案用于他的链接问题,即:
As pointed out by Dave
you can use the proposed solution to his linked question, i.e. by doing:
<%= javascript_include_tag params[:controller] %>
你必须要记住的唯一事情是将你的javascript资源命名为控制器 - 所以 home.js
和 sessions.js
在你的情况下(如果我正确记得Rails的命名约定) 。
The only thing you'd have to remember to do this is to name your javascript assets the names of the controllers - so home.js
and sessions.js
in your case (if I remember Rails' naming conventions correctly).
我已经看到了其他方法,如果你想在不同控制器的页面上包含一些javascript,无论出于什么原因,这都很有用。 这个答案,我想想,给出一个非常优雅的解决方案。
I have seen other ways of doing this though, which is useful if you want to include some javascript on pages associated with different controllers for whatever reason. This answer, I think, gives a very elegant solution.
首先,将全局javascripts添加到清单文件中,并将其包含在 application.html中。 erb
布局文件。
First off, add the global javascripts to your manifest file, and include that in your application.html.erb
layout file.
<html>
<head>
# stuff
<%= javascript_include_tag 'application' %>
<%= yield :javascripts %>
</head>
<body>
<%= yield :content %>
</body>
</html>
然后在您要加载特定javascripts的视图中,只需添加以下内容:
And then in the views where you would load specific javascripts simply add the following:
<% content_for :javascripts do %>
<%= javascript_include_tag 'your_script' %>
<% end %>
这篇关于在rails中为每个控制器加载Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!