Is there an accepted way for generating the javascript in the application layout, dependent upon what the controller/action is?
-
Your question would be better if we could see a sample of the javascript you're talking about.Ryan Bigg– Ryan Bigg2011-01-18 07:21:44 +00:00Commented Jan 18, 2011 at 7:21
-
Do you mean you want to include different javascript files for different views?Swanand– Swanand2011-01-18 07:31:05 +00:00Commented Jan 18, 2011 at 7:31
2 Answers
content_for is the right way to go about here. Based on the current action you could include javascripts required for the particular view. Also however it should be only in the head as loading javascripts in the middle of the page is considered to be obtrusive and hence have a content for in the head of the page. like
<head> <%= yield :dynamic_javascripts %> </head>
and
<% content_for :dynamic_javascripts do %>
<%= javascript_include_tag "javascript.js" %>
<%end%>
Comments
In your application layout you need a "yield" like this:
<html>
<head>
<%= yield :head %>
</head>
<body>
</body>
</html>
Then in your controller views you can specify the specific javascript files for that view using:
<% content_for :head do %>
<%= javascript_include_tag "my_javascript_file.js" %>
<% end %>
The content_for method allows you to insert content into a named yield block in your layout.