【问题标题】:Create a table using a list of elements使用元素列表创建表格
【发布时间】:2014-03-31 20:51:04
【问题描述】:

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

使用hamlerb 的最佳方法是什么?我也在使用引导程序,所以如果有一种使用该框架的简单方法可以做到这一点,那可能会很好。

【问题讨论】:

  • @locoboy- 你在说这样的事情吗? getbootstrap.com/2.3.2/base-css.html#tables
  • 是的,但它必须是动态的,因为列表大小不断变化。
  • 假设您有一系列要在表格中显示的内容。您将如何格式化视图,以便在遍历数组时它会填充表格而不是项目列表。

标签: ruby-on-rails twitter-bootstrap haml


【解决方案1】:

这是我使用 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-14
    • 2014-02-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多