Posted by
jvnill
on
July 30, 2010
Use content_for for grouping html contents like javascript and css
you should have a
<%= yield :head %>
line in your head tag so you can do
<% content_for :head do %>
<%= javascript_include_tag 'foo', 'bar' %>
<% javascript_tag do %>
page specific javascript here
<% end %>
<% end %>
in any page you like to include a javascript/css file. This way, all js and css files/code is found in the head tag of your page.
In the same way, you can have a partial that renders the sidebar of your application. In that partial, you can have
# Common sidebar items here
# Common sidebar items here
# Dynamic sidebar items here
<%= yield :sidebar %>
so you can have dynamic sidebar content by just adding
<% content_for :sidebar do %>
page specific sidebar content
<% end %>

Comments
Also I would suggest a best practice would be to have a content_for :footer in addition to content_for :head. Then put the JavaScript (along with other things like Google Analytics and other embed code) in the footer. This is better for performance as rendering the page is not blocked while the JavaScript downloads.
Also don't forget that multiple calls are automatically concatenated. So you can call content_for(:head) as often as you want and then have a single yield :head to render all the header pieces.
This way I can optionally override these areas with content_for blocks in my view. One's I don't override will use the default content.