我有一个定期更改的元素列表,而不是以列表格式显示它们(每行一个列表元素)我想以表/网格格式显示它(每行3-4个元素)。
使用haml
或erb
执行此操作的最佳方式是什么?我也在使用bootstrap,所以如果使用该框架有一个简单的方法,那可能会很好。
答案 0 :(得分:0)
这是我与Haml和Bootstrap(两个不同版本)的解决方案。 Ruby each_slice
方法做了很多工作。
我有大陆和国家模型。在Continent页面上,我在表格中显示给定大陆的所有国家/地区。表中的列数在Continent模型中的模型方法中定义。
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
Haml的:
.row
.col-md-12
%table.table
%tbody
- @country_rows.each do |country_row|
%tr
- country_row.each do |country|
%td= country
continent.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(第2版):
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(第2版):
.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