Am testing the content_for in my rails 3.2 app and following the rails guides but they are specific to the actual files and I cannot seem to get the yield to work:
application.html.erb file:
<!DOCTYPE html>
<html>
<head>
...
</head>
<body>
<%= yield :navigation %> #shouldn't this load the content_for block named :navigation specified in the _main_nav.html.erb partial?
<%= yield %> #this load the index page content
</body>
</html>
I created a layout file _main_nav.html.erb (i know I can render with <%= render 'layouts/header' %> but I am trying to use the content_for instead) The _main_nav.html.erb is:
<% content_for :navigation do %>
<ul>
<li>Home</li>
</ul>
<% end %>
They way I read the RailsGuide http://guides.rubyonrails.org/layouts_and_rendering.html#using-the-content-for-method this should work. But it does not. I do not get an error. Seems simple but I am stumped.
When I go to my index.html.erb file I would expect to see this result:
OK, I think I have a solution for this. Your code:
<% content_for :navigation do %>
<ul>
<li>Home</li>
</ul>
<% end %>
should be at the top of the file that is loading. Your _header.html.erb is a partial. If you move this code into views/tasks/new.html.erb then it works as expected.
However, for it to work as you want, then you need to adjust your application.html.erb file:
<p>this is where we should see the "Home" link appear that is defined in _header.html.erb:</p>
<section class="header">
<% render 'layouts/header' %>
<%= yield :navigation %>
</section>
Notice, that I have called the render erb tag without the = sign. This means I don't see the contents of the header partial, but it does load. If you include the = sign then it still works but also renders any other content you may have in the partial. Note: The render tag has to be above/before the yield tag.