Search code examples
ruby-on-railsyieldcontent-for

Rails: Using Yield, Calling Multiple View Pages


Problem: How Do You Render Multiple View Pages From Different Controllers?

In my views/layouts/application.html.erb, I call views/posts/index.html.erb with the yield method.

<div class='span10'>
    <%= yield %>
</div>

On top of it, I wanted to call views/good_posts/index.html.erb with yield. So in that particular index file, I wrap around all the code with content_for method.

<%= content_for :good_post do %> all my content in good_post/index.html.erb <% end %>

I go back to application.html.erb, I tried to call the index file of good_post with yield method.

<div class='span10'>
    <%= yield :good_post %>
</div>
<div class='span10'>
    <%= yield %>
</div>

I thought this would result in good_post/index to be rendered on top of post/index, but it did not work; only post/index was correctly rendered as before. Could someone explain why this is, and tell me the correct way to approach this problem? I appreciate your help!


Solution

  • You should, as @cdesrosiers said, rename the index.html.erb file in good_posts to _index.html.erb. Then you can render this view in your application like this:

    <div class='span10'>
        <%= render 'good_posts/index' %>
        <%= yield :good_post %>
    </div>
    <div class='span10'>
        <%= yield %>
    </div>
    

    Personally, I would change the index.html.erb file in good_posts folder to _good_posts.html.erb file in app/views/posts folder. Your code will have better meaning, and you can know where to find it after, because it relates to posts. So, if you change this, use this code:

    <div class='span10'>
        <%= render 'posts/good_posts' %=
        <%= yield :good_post %>
    </div>
    <div class='span10'>
        <%= yield %>
    </div>
    

    Another you should change is content_for :good_post -> content_for :good_posts , because good posts maybe have many posts, so you should use post in pluralize.