首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用元素列表创建表

使用元素列表创建表
EN

Stack Overflow用户
提问于 2014-04-01 04:51:05
回答 1查看 708关注 0票数 0

我有一个定期变化的元素列表,而不是以列表格式显示它们(每行一个列表元素),我想以表格/网格格式(每行3-4个元素)显示它们。

使用hamlerb实现此目的的最佳方法是什么?我也在使用bootstrap,所以如果有一种简单的方法可以使用该框架来实现这一点,那就更好了。

EN

回答 1

Stack Overflow用户

发布于 2014-05-09 18:56:35

这是我对Haml和Bootstrap (两个不同版本)的解决方案。Ruby each_slice方法完成了这项繁重的工作。

我有大陆版和乡村版。在Continent页面上,我在表中显示给定大陆的所有国家/地区。表中的列数是在Continent模型的model方法中定义的。

continents_controller.rb:

代码语言:javascript
复制
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

哈默尔:

代码语言:javascript
复制
.row
  .col-md-12
    %table.table
      %tbody
        - @country_rows.each do |country_row|
          %tr
            - country_row.each do |country|
              %td= country

continent.rb:

代码语言:javascript
复制
class Continent < ActiveRecord::Base
    ...
    def self.number_of_table_columns
      4
    end
end

Html输出(示例):

代码语言:javascript
复制
  <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 (第二版):

代码语言:javascript
复制
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 (第二版):

代码语言:javascript
复制
.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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22771924

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档