I have multiple partials which may or may not be included in a given layout... and they often have javascript required for just the content of that partial... but I want the javascript loaded in the head.
so I'll generally have something like:
<html>
<head>
<title><%= @page_title %></title>
<%= yield :head %>
</head>
...etc
and in partial 1:
<% content_for :head do %>
<%= javascript_tag 'partial_one_js' %>
<% end %>
and in partial 2:
<% content_for :head do %>
<%= javascript_tag 'partial_two_js' %>
<% end %>
But whichever is defined second blows away the content coming from the first.
There is no way to combine the partials.
I'd like to be able to concatenate them without doing something totally hacky. It also has to work if only one or neither is present.
... and I'd especially rather avoid:
<html>
<head>
<title><%= @page_title %></title>
<%= yield :head_one %>
<%= yield :head_two %>
</head>
... ick
So... does anybody have a solution?
The best practice is to use yield in your layouts, and content_for in your views. There is a special second use for content_for , where you give it no block and it returns the previously rendered content. This is primarily for use in helper methods where yield cannot work.
Without any arguments, yield will render the template of the current controller/action. So if you're on the cars/show page, it will render views/cars/show. html. erb . When you pass yield an argument, it lets you define content in your templates that you want to be rendered outside of that template.
Use content_for
to retrieve the stored content rather than yield
.
<html>
<head>
<title><%= @page_title %></title>
<%= content_for :head %>
</head>
...etc
From the source docs:
# Note that content_for concatenates the blocks it is given for a particular
# identifier in order. For example:
#
# <% content_for :navigation do %>
# <li><%= link_to 'Home', :action => 'index' %></li>
# <% end %>
#
# <%# Add some other content, or use a different template: %>
#
# <% content_for :navigation do %>
# <li><%= link_to 'Login', :action => 'login' %></li>
# <% end %>
#
# Then, in another template or layout, this code would render both links in order:
#
# <ul><%= content_for :navigation %></ul>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With