1

似乎rails 3方式是将所有javascript全局包含到应用程序中。我对此是否正确?

原因是什么?

如果我不正确,包含特定于页面的 javascript 的标准方法是什么?

谢谢!

4

4 回答 4

1

默认情况下,Rails 3 将包含application.js,其中包含//= require_tree使其依赖于/app/assets/javascripts中的所有其他 JS 文件。

//= require_tree您可以在application.jsapplication.html.erb中删除并通过添加以下内容来包含特定于控制器的 JS <%= javascript_include_tag "application" %>

<%= javascript_include_tag params[:controller].split("/")[0])

然后,为每个控制器制作 JS 文件 ( app/assets/javascripts/CONTROLLER-NAME.js ),其中包含:

  1. //= require application
  2. 特定于控制器的 JS

这些将依赖于application.js,但也可以有自己的 JS。

.split方法允许像 Devise 这样的控制器在 / 之前使用他们的名字作为 .js 文件的名称,因此您只需创建devise.js而不是devise /sessions.js等。

于 2012-12-13T03:38:42.900 回答
0

You could use the content_for tag to add page specific content to the head of the page.

In your

application.html.erb (your layout file) under your javascript includes you add a line that says

<%= content_for :js_include %>

then in any page you want to include a page specific javascript you just do

<% content_for :js_include do %>
  <%= javascript_include_tag "some_javascript_file" %>
<% end %>

I'm not sure if you have to inlcude the = sign on the javascript_include_tag (just make sure you put it as it is on the application.html.erb file but that's pretty much the gist of it. Using content_for tags

EDIT

Some helpful links

Railscasts Episode Layouts and Content For

Rails API content_for

于 2012-12-13T03:31:15.383 回答
0

很多种方法:

<%= javascript_tag "...javascript..." %>
* Generates <script type="text/javascript">...javascript...</script>

或者

<% content_for :script do %>
   ...javascript...
<% end %>
* This approach includes script into <%= yield :script %> defined in the template anywhere, for example inside the <head> dom:
<head>
  ...
  <% if content_for?(:script) %>
    <%= javascript_tag yield(:script) %>
  <% end %>

</head>

或许多其他方式。

于 2012-12-13T03:36:40.000 回答
0

要将特定 javascript 文件仅包含到特定视图页面中,您需要执行以下过程。

i) In the assets folder create a separate folder eg. 'separate_view' , and inside put your specific js, and css files.

ii) In the application lay out write like following for 'separate_view'.
  <%= yield :separate_view %>

iii) In your target template write the following for 'separate_view'.
  <% content_for (:separate_view) do %>
    <%= javascript_include_tag "xxx.js" %>
    <%= stylesheet_link_tag "xxx.css" %>
  <%end%>

以上内容适用于您的特定视图文件。

于 2012-12-13T05:20:18.517 回答