Search code examples
ruby-on-railsrubydo-loops

How to display specific range in do loop in Ruby?


I'm having trouble display specific range of data in do-loop in Ruby. I Have this example code:

Post

<!-- Display loop only 9 sections -->
<div class="row">
<% @post.each do |post| %>
    <div clas="blog">
        <h3 class="heading"><%= post.title %></h3>
    </div>
</div>
<!-- END => Display loop only 9 sections -->

<div class="row">
    <div clas="banner">
        <img src="images/banner.jpg" alt="banner">
    </div>
</div>

<!-- Continue display loop for 10 and until latest sections -->
<div class="row">
<% @post.each do |post| %>
    <div clas="blog">
        <h3 class="heading"><%= post.title %></h3>
    </div>
</div>
<!-- END => -->

In this situation I want to add a banner section after it displays 9 posts:

<div class="row">
    <% @post.each do |post| %>
        <div clas="blog">
            <h3 class="heading"><%= post.title %></h3>
        </div>
    </div>
    <!-- END => Display loop only 9 sections -->

<!-- I will add this banner section after posts displays 9 posts -->
<div class="row">
        <div clas="banner">
            <img src="images/banner.jpg" alt="banner">
        </div>
    </div>

and then I want to continue the post display from post 10 up to latest posts after I added the banner section:

<!-- Continue display loop for 10 and until latest sections -->
<div class="row">
<% @post.each do |post| %>
    <div clas="blog">
        <h3 class="heading"><%= post.title %></h3>
    </div>
</div>
<!-- END => -->

In my situation, the two post sections will display all the data in post. How do you limit 9 posts in the 1st div element, and continue the latest posts in the 3rd div element below the banner section using the do loop? I want to continue the latest posts in my 3rd section.

Is there any easy way to do this?

I'm currently new to rails app and I'm still exploring the syntax of the program.


Solution

  • For the first 9 posts:

    <% @post.limit(9).each do |post| %>
    

    And the other posts below the banner:

    <% @post.drop(9).each do |post| %>