我正在创建一个用于打印标签的视图。我有一个HTML格式的/CSS格式的表,它具有5个标签的2列的正确尺寸:
<div id="inventory_labels">
<table class="table-bordered" id="avery8163">
<thead>
<tr>
<td style='width: .155in;'></td>
<td style='width: 4in;'></td>
<td style='width: .19in;'></td>
<td style='width: 4in;'></td>
<td style='width: .155in;'></td>
</tr>
</thead>
<tfoot>
<tr>
<td colspan="5"></td>
</tr>
</tfoot>
<tbody>
<% 40.times do # just a placeholder for the actual loop / partial %>
<tr>
<td></td>
<td>LABEL #1 (should be a record)</td>
<td></td>
<td>LABEL #2 (should be a record)</td>
<td></td>
</tr>
<% end %>
</tbody>
</table>
</div>
和SCSS:
#inventory_labels {
width: 8.5in;
margin-right: auto;
margin-left: auto;
}
table#avery8163 {
table-layout: fixed;
width: 8.5in;
thead, tfoot {
td {
height: .5in;
}
}
tbody {
td {
height: 2in;
}
}
}
@media print {
table#avery8163 {
thead {
display: table-header-group;
}
tfoot {
display: table-footer-group;
}
}
}
我想使用分部来循环<tbody>
中的记录,但我需要一次循环2个,每个"LABEL"一个。
有什么建议或想法吗?
我确实把它格式化为div(就像黑暗时代的这种策略(,而不是表列,但由于页边空白和排水沟排列不好,数学变得非常混乱。
首次运行
这真的很难看,对吧?
@counts
是我想要循环通过的记录的ActiveRecord数组,在控制器中定义。
<tbody>
<% n = 0 %>
<% @loop.times do # @loop = (@counts.count/2).ceil %>
<tr>
<td></td>
<td>
<%= render partial: 'label', locals: { count: @counts[n] } %>
<% n += 1 %>
</td>
<td></td>
<td>
<% if @counts[n].present? %>
<%= render partial: 'label', locals: { count: @counts[n] } %>
<% end %>
<% n += 1 %>
</td>
<td></td>
</tr>
<% end %>
</tbody>
既然将集合用作数组不是问题,那么可以使用in_groups_of
方法https://api.rubyonrails.org/classes/Array.html#method-的i-in_groups_o
<% @objects.in_groups_of(2, false) do |obj1, obj2| %>
<tr>
<td></td>
<td><%= #something with obj1 %></td>
<td></td>
<td><%= #something with obj2, you should check if it's not nil though if the array has an odd length %></td>
<td</td>
</tr>
<% end %>