如何在Rails 3.1中显示控制器特定的javascript? [英] How to display controller specific javascript in rails 3.1?

查看:58
本文介绍了如何在Rails 3.1中显示控制器特定的javascript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的资产文件夹结构如下

I have my assets folder structure like this

assets
  javascripts
    products
      --product.js
      --productValidate.js
    store
      --store.js

我希望仅当调用产品控制器中的操作时才将project.js和projectValidate.js作为资产管道的一部分添加到application.js中,而当调用商店控制器中的操作时要将store.js添加到资产管道中.如何在Rails 3.1中实现此目标?

I want the project.js and projectValidate.js to be added in my application.js as a part of asset pipe-lining only when actions in product controller is called and store.js when actions in store controller is called. How can i achieve this in rails 3.1?

推荐答案

正如Rahul所述,application.js是预编译的,并且对于每个操作都是相同的. 因此,它不依赖于特定的控制器. Application.js应包含所有(或大部分)操作所需的javascript.

As Rahul already mentioned, application.js is precompiled and the same for every action. So it does not depend on a particular controller. Application.js should contain the javascript you need for all (or most) of your actions.

但是,您可以使用嵌套布局扩展应用程序布局.让我们假设以下结构:

However, you may expand your application layout with nested layouts. Let us assume the following structure:

... app/view/layouts/application.html.erb ...

<html>
<head>
  <%= javascript_include_tag 'application' %>
  <%= yield :javascripts %>
  <%= stylesheet_link_tag 'application' %>
  <%= yield :stylesheets %>
</head>
<body>
  <%= yield %>
</body>
</html>

和一个:

... app/view/layouts/products.html.erb ...

<% content_for :stylesheets do %>
  <%= stylesheet_include_tag 'products' %>
<% end %>
<% content_for :javascripts do %>
  <%= javascript_include_tag 'products' %>
<% end %>
<%= render :template => 'layouts/application' %>

因此,您只需要在products-files中添加/要求您的样式表和javascript. 注意,这里的所有代码都应阅读为伪代码,我没有对其进行测试.

So you just have to add/require your stylesheets and javascripts in the products-files. Notice, all code here should be read as pseudo-code, I did not test it.

来自官方"渲染指南的信息.

这篇关于如何在Rails 3.1中显示控制器特定的javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆