我在显示数据方面遇到了问题,就像这里描述的那样,但我的对象在数字上没有方便的标注:How do I iterate over an unknown object in a Meteor Spacebars template?
数据可能不止一次嵌套,可能会有所不同,但总是以数组结尾。 我也对新的数据结构持开放态度。
示例数据:
{
"Category A":
{
"Sub-Category1":
{
"Sub-Sub-Category1": ['Value1', 'Value2']
},
"Sub-Category2":
{
"Sub-Sub-Category2": ['Value3'],
"Sub-Sub-Category3": ['Value4']
}
},
"Category B":
{
"Sub-Category1": ['Value5']
}
}
答案 0 :(得分:1)
您需要一个递归模板来处理任意嵌套,一个枚举对象键的帮助器,以及一个获取与键对应的父对象值的帮助器。
HTML:
<template name="nest">
{{#if isArray}}
{{#each this}}
{{this}} <!-- we're assuming that array elements aren't themselves objects -->
{{/each}}
{{#elseif isObject}}
{{#each keys}}
{{#with value}}
{{> nest }}
{{/with}}
{{/each}}
{{else}} <!-- catch the case of a scalar key value (no array) -->
{{this}}
{{/if}}
</template>
JS:
Template.nest.helpers({
isArray(){
return typeof(this) === "object" && this.length && this.length > 0;
},
isObject(){
return typeOf(this) === "object" && !this.length;
},
keys(){
return Object.keys(this); // returns an array of strings
},
value(){
return Template.parentData()[this]; // look up the hierarchy to get the parent object then select the data for the current key
}
});