简体   繁体   中英

How to use each_slice in ERB to set rows?

I have an array of the following:

[{title, description, body, image}, 
 {title2, description2, body2, image2}, 
 {title3, description3, body3, image3}, 
 {title4, description4, body4, image4}]

In my ERB I'm trying to get the first two on the same row. The next two on the next row. Basically having image 1 and 2 side by side on one row, image 3 and 4 side by side on the row beneath.

So I have something like the following:

<% @post.each_slice(2) do |post, b| %>
  <% if b.sort_order != 5 %>
    <%= image_tag b.post_image %>
    <%= b.title %>
    <%= b.description %>
    <%= b.body %>
  <% end %>
<% end %>

Cool this gets me the 2 and 4 position in the array but really I'd like to see:

[1, 2]
[3, 4]

So I changed it to do:

<% @post.each_slice(2) do |post, b| %>
  <% if b.sort_order != 5 %>
    <%= image_tag post.post_image %>
    <%= image_tag b.post_image %>
  <% end %>
<% end %>

Cool so now I'm getting [1,2] [3,4] . How do I get it to display:

Title 1         Title 2
Description 1   Description 2

Try the following:

<% @post.each do |post| %>
  <% if post.sort_order != 5 %>
    <div class="half-width">
      <%= image_tag post.post_image %>
      <%= post.title %>
      <%= post.description %>
      <%= post.body %>
    </div>
  <% end %>
<% end %>

And add the following CSS:

.half-width {
  display: inline-block;
  width: 50%;
}

Be aware the 50% width takes into account any whitespace, so it might still split lines. Have a play and see what you think - a little more info here .

So the resolution is actually a CSS issue. I "solved it" by adding breaking it out further to something like:

<% @post.each_slice(2) do |post, b| %>
<% if b.sort_order != 5 %>

  <div class="col-md-6">
  <%= image_tag post.post_image %>
  </div>

  <div class="col-md-6">
  <%= image_tag b.post_image %>
  </div>

 <% end %>

Basically I was an idiot in only seeing it as lumped together in the erb.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM