本文介绍了从Ruby中的哈希数组生成HTML表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
从散列数组生成HTML表格的最佳方法(理想情况下是宝石,但必要时是代码片段)是什么?
What's the best way (ideally a gem, but a code snippet if necessary) to generate an HTML table from an array of hashes?
例如,此数组哈希:
[{"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>
推荐答案
使用XMLBuilder:
Use the XMLBuilder for this:
data = [{"col1"=>"v1", "col2"=>"v2"}, {"col1"=>"v3", "col2"=>"v4"}]
xm = Builder::XmlMarkup.new(:indent => 2)
xm.table {
xm.tr { data[0].keys.each { |key| xm.th(key)}}
data.each { |row| xm.tr { row.values.each { |value| xm.td(value)}}}
}
puts "#{xm}"
输出
<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>
这篇关于从Ruby中的哈希数组生成HTML表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!