我有一个定期变化的元素列表,而不是以列表格式显示它们(每行一个列表元素),我想以表格/网格格式(每行3-4个元素)显示它们。
使用haml或erb实现此目的的最佳方法是什么?我也在使用bootstrap,所以如果有一种简单的方法可以使用该框架来实现这一点,那就更好了。
发布于 2014-05-09 18:56:35
这是我对Haml和Bootstrap (两个不同版本)的解决方案。Ruby each_slice方法完成了这项繁重的工作。
我有大陆版和乡村版。在Continent页面上,我在表中显示给定大陆的所有国家/地区。表中的列数是在Continent模型的model方法中定义的。
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= countrycontinent.rb:
class Continent < ActiveRecord::Base
...
def self.number_of_table_columns
4
end
endHtml输出(示例):
<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)
...
endHaml (第二版):
.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.namehttps://stackoverflow.com/questions/22771924
复制相似问题