Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display controller specific javascript in rails 3.1?

I have my assets folder structure like this

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

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?

like image 655
Rahul Avatar asked Sep 05 '11 20:09

Rahul


3 Answers

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>

and a:

... 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' %>

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.

Information taken from the "official" Render-Guide.

like image 103
Deradon Avatar answered Nov 14 '22 06:11

Deradon


As far as I know assets pipilene is something that should be precompiled. So... conceptually it should take all files at once and return just one copiled file, and it is good for caching.

You can store them somewhere out od assets (in puplic, as older Rails do, for example) and include it in depending to current controller and action

like image 31
fl00r Avatar answered Nov 14 '22 06:11

fl00r


I like the approach mentioned in the answer to this question:

Rails 3.1 asset pipeline: how to load controller-specific scripts?

like image 1
cailinanne Avatar answered Nov 14 '22 06:11

cailinanne