动态显示一个html表中的散列数组? [英] Dynamic display of an array of hashes in a html table?
问题描述
我有一个名为products的数据库,它有一个使用名为 data
的hstore的字段。
现在,在我的index.html.haml中,我只是遍历产品并将它们的 data
显示为一个哈希值:
- @ products.each do | product |
= product.data#这是打印一个哈希
%hr
例如,可以打印一个散列,如:
{Name=>Example,type=> book,price=>7.99}
我想制作一个可以容纳动态数量的键和值的HTML表,并将它们打印成具有与键相对应的值的列。下面是一张图:
感谢您的帮助!
/ p>
解决方案1:基于相同的.data内容#弃用
条件:
- 所有product.data都具有相同数量的键/值对。
- 所有产品的配对都是相同的。
代码:
#标题
%tr
- @ products.first.data.keys.each do | attribute_name |
%th = attribute_name
#body
- @ products.each do | product |
%tr
- product.data.attributes.each do | attribute_value |
%td = attribute_value
如果每个
具有相同数量的键/值对并存储在相同顺序中。 h1>解决方案2:完全动态(.data变化)#推荐
条件: 随意查询详情,我感觉就像我给了你一段代码,没有任何解释...... I have a database called "products" that has a field that uses hstore called At the moment, in my index.html.haml, I'm just looping through products and displaying their Which, for example, could print a hash like: I'd like to make a HTML table that could hold a dynamic number of keys and values, and print them into columns with values corresponding to keys. Here's a diagram: Thanks for all help! Hope this can help: Conditions: The code: This code will render properly if each Conditions: The code: Feel free to ask for details, I feel like I just gave you a piece of code without any explanation... 这篇关于动态显示一个html表中的散列数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
#我们收集数据哈希中所有可能的属性名称:
- headers = @ products.map(&:data).flat_map(&:keys).uniq
%tr
#我们为每个属性的名称创建一个表头元:
- headers.each do | key |
%th =关键
- @ products.each do | product |
%tr#为每个属性的名称,我们显示一个TD单元并尝试显示它的值,如果存在的话
- headers.each do | key |
%td = product.data [key]
data
.data
as a hash:- @products.each do |product|
=product.data #THIS PRINTS A HASH
%hr
{"Name"=>"Example","type"=>"book", "price"=>"7.99"}
Solution 1: based on same .data content # Deprecated
# headers
%tr
- @products.first.data.keys.each do |attribute_name|
%th= attribute_name
# body
- @products.each do |product|
%tr
- product.data.attributes.each do |attribute_value|
%td= attribute_value
product.data
has the same amount of key/value pairs AND stored in the same order.
Solution 2: fully dynamic (.data varying) # Recommended
# we gather all possible attribute's name in the data hash:
- headers = @products.map(&:data).flat_map(&:keys).uniq
%tr
# we make a table-head cell for each attribute's name:
- headers.each do |key|
%th= key
- @products.each do |product|
%tr # for each attribute's name, we display a TD cell and try to display it's value if exists
- headers.each do |key|
%td= product.data[key]