【问题标题】:Ruby Array to HTML table including headerRuby 数组到 HTML 表,包括标题
【发布时间】:2013-04-19 22:34:33
【问题描述】:

我正在尝试将我从 CSV 文本输入中解析出来的 ruby​​ 数组呈现为 HTML 表格。

解析已将输入分离为具有相等列的行数组,从中创建了一个行数组数组。

演示文稿需要容纳行或列的任意组合,并将第一个数组(索引 = 0)视为表头。

这是在我的模型中:

class Size < ActiveRecord::Base

attr_accessor :chart_options, :test
attr_accessible :account_id, :chart, :name

belongs_to :account

def test
'<it>hello</it>'
end


def chart_options

require 'csv'   

@chart_options = CSV.parse(chart , {:headers => true, :col_sep => "|", :row_sep     => :auto, :skip_blanks => true})

@table = CSV.parse(chart, {:headers => true, :col_sep => "|", :row_sep => :auto, :skip_blanks => true}).to_a

@chart_options
@table

end

end

这是输出:

["UK ", " USA ", " Euro "]
["Small UK ", " Small US ", " Small Euro "]
["Med UK ", " Med US ", " Med Euro "]
["Large UK ", " Large US ", " Large Euro"]

更新的解决方案:

<table class="size_chart table table-striped">
    <thead>
        <tr>
          <% @headers.each do |header| %>
            <th><%= header %></th>
          <% end %>
        </tr>
    <thead>
    <tbody>
        <% @rows.each do |row| %>
          <tr>
            <% row.each do |column| %>
              <td><%= column %></td>
            <% end %>
            </tr>
          <% end %>
    </tbody>
</table>

【问题讨论】:

  • 你要什么?

标签: html ruby-on-rails arrays html-table


【解决方案1】:
<table>
<tr>
  <% @table.delete_at(0).each do |header| %>
    <th><%= header %></th>
  <% end %>
</tr>
<% @table.each do |row| %>
  <tr>
    <% row.each do |column| %>
      <td><%= column %></td>
    <% end %>
  <% end %>
</table>

警告:我没有测试过这段代码,所以可能有错别字,但这是大体思路,循环中的循环。

【讨论】:

  • 感谢您的快速回答。迭代 2 个数组有效。我在上面的最终代码中包含了 sn-p。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多