"v1", "col2"=>"v2"}, {"col1"=>-6ren">
gpt4 book ai didi

ruby-on-rails - 从 Ruby 中的哈希数组生成 HTML 表

转载 作者:数据小太阳 更新时间:2023-10-29 06:42:39 26 4
gpt4 key购买 nike

从哈希数组生成 HTML 表格的最佳方法是什么(最好是 gem,但如果需要,也可以是代码片段)?

例如,这个哈希数组:

[{"col1"=>"v1", "col2"=>"v2"}, {"col1"=>"v3", "col2"=>"v4"}]

应该产生这个表:

<table>
<tr><th>col1</th><th>col2</th></tr>
<tr><td>v1</td><td>v2</td></tr>
<tr><td>v3</td><td>v4</td></tr>
</table>

最佳答案

# modified from Harish's answer, to take care of sparse hashes:

require 'builder'

def hasharray_to_html( hashArray )
# collect all hash keys, even if they don't appear in each hash:
headers = hashArray.inject([]){|a,x| a |= x.keys ; a} # use array union to find all unique headers/keys

html = Builder::XmlMarkup.new(:indent => 2)
html.table {
html.tr { headers.each{|h| html.th(h)} }
hashArray.each do |row|
html.tr { row.values.each { |value| html.td(value) }}
end
}
return html
end

关于ruby-on-rails - 从 Ruby 中的哈希数组生成 HTML 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2634024/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com