簡體   English   中英

在rails中使用.each循環時如何將兩個元素連續放置

[英]How to place two elements in a row while using .each loop in rails

我想在使用'.each'方法時每行顯示兩列代碼在表數據標記“”中。 但問題是以下代碼連續顯示一列。

<table>
  <% @lease.apartment.roommates.each do |roommate| %>
    <tr>
      <td colspan="5">
        <% unless roommate == @lease.second_occupant || roommate == @lease.user %>        
          <% if roommate.current_room.present? %>
            <p>
              <%= roommate.full_name %> - 
              <% if roommate.current_room.apartment == @lease.apartment%>
                <%= roommate.current_room&.label %> 
              <% end %>
              <br>Email:<%= roommate.email %><br>Phone:<%= roommate.phone %><br>
              <% if @lease.end_at.present? %>
                Lease End date (if applicable):<%= @lease.end_at %>
              <% end %>
            </p>
          <% end %>
        <% end %>
      </td>
    </tr>
  <% end %>
</table>

您可以使用each_slice方法將數組划分為每個包含 2 個元素的切片:

<table>
  <% @roommates.each_slice(2) do |roommate_slice| %>
    <tr>
      <td colspan="5">            
        <%= roommate_slice[0].full_name %>
        <%= roommate_slice[1].full_name %>
      </td>      
    </tr>
  <% end %>
</table>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM