簡體   English   中英

在rails中使用.each方法時如何將兩列連續放置

[英]How to place two columns in a row while using .each method 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>

您可以這樣做,以便連續獲得兩列

<table>
<% @lease.apartment.roommates.each_with_index do |roommate, i| %>
  <% if (i+1)%2 == 1%>
  <tr>
  <% end %>
    <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>
  <% if (i+1)%2 == 0%>
  </tr>
  <% end %>

<% end %>

嗨,您可以使用each_slice評論中提到的each_slice

<table>
  <% @lease.apartment.roommates.each_slice(2) do |roommate_pair| %>
    <% roommate_pair.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 %><be>
                <% if @lease.end_at.present? %>
                  Lease End date (if applicable):<%= @lease.end_at %>
                <% end %>
              </p>
            <% end %>
          <% end %>
        </td>
      </tr>
    <% end %>
  <% end %>
</table>

我希望這能幫到您。

暫無
暫無

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

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