这是我使用 Haml 和 Bootstrap(两个不同版本)的解决方案。 Ruby each_slice 方法完成了艰苦的工作。
我有 Continent 和 Country 模型。在大陆页面上,我在表格中显示给定大陆的所有国家/地区。表格中的列数在大陆模型中的模型方法中定义。
continents_controller.rb:
def show
@continent = Continent.find(params[:id])
@country_rows = Country.where(:continent_id => params[:id]).map {|c| c.name}.each_slice(Continent.number_of_table_columns).to_a
...
end
哈姆:
.row
.col-md-12
%table.table
%tbody
- @country_rows.each do |country_row|
%tr
- country_row.each do |country|
%td= country
大陆.rb:
class Continent < ActiveRecord::Base
...
def self.number_of_table_columns
4
end
end
HTML 输出(示例):
<div class='row'>
<div class='col-md-12'>
<table class='table'>
<tbody>
<tr>
<td>Spratly Islands</td>
<td>Vietnam</td>
<td>Azerbaijan</td>
<td>Georgia</td>
</tr>
<tr>
<td>Sri Lanka</td>
<td>Israel</td>
<td>Cyprus</td>
<td>Yemen</td>
</tr>
<tr>
<td>Maldives</td>
<td>Kuwait</td>
<td>West Malaysia</td>
<td>Nepal</td>
</tr>
...
</tbody>
</table>
</div>
</div>
这是另一个更方便的替代方法,因为可以在视图中访问 Country 对象:
continents_controller.rb(第二版):
def show
@continent = Continent.find(params[:id])
@country_rows_2 = Country.where(:continent_id => params[:id]).each_slice(Continent.number_of_table_columns)
...
end
Haml(第二版):
.row
.col-md-12
%table.table
%tbody
- @country_rows_2.each do |country_row_2|
%tr
- country_row_2.each do |country_2|
%td= country_2.name