I have thought about this for a while. I’ve not implemented it,
but it’s along the lines of the content_for method. This is
untested and at the moment just my mind rambling
Robert,
Yes, I use this code regularly in all of my rails apps. As far as I know, the view code is always run before the layout code. If you tried something similar or tried the code I posted, and it failed, I would be willing to help you debug it, just tell me how it failed.
I have just released a really simple plugin for this. It ensures that there is no duplication of javascripts. Stylesheets can also be included similarly.
Ok I’ve had a chance to play with it and I’ve found a way that it can be done. It’s a bit of hackery though.
You can put a yield call in your head tag so that you can get javascripts there. But, before your yield in the head tag, you need to render your partials. You can put them elsewhere in your layout by including these into content_for blocks.
In your layout (HTML interspersed where ever )
<% content_for :my_partial do %>
<%= render :partial => ‘my_partial’ -%>
<% end %>
<%= yield :javascripts %>
<%= yield :my_partial %>
In the context of the plugin that I released, if your interested. (I’ve changed the method names since last night. I wasn’t entirely satisfied with them)
<% content_for :my_partial do %>
<%= render :partial => ‘my_partial’ -%>
<% end %>
<%= require_on_demand %>
<%= yield :my_partial %>
and then anywhere in your partial, or views
<% require_javascript “my”, “javascript”, :defaults %>
This content_for and yield looks overly complicated to me. In
particular, as content_for does not do much more than set an instance
variable. A tiny bit of code in ApplicationHelper does all that's
necessary.
Michael
# app/helpers/application_helper.rb
module ApplicationHelper
def require_js(*js)
@required_js ||=
@required_js |= js
end
def require_css(*css)
@required_css ||=
@required_css |= css
end
def include_required_js
javascript_include_tag(*@required_js)
end
def include_required_css
stylesheet_link_tag(*@required_js)
end
end