在 blaze 中迭代 json 对象数组
Iterate over a json object array in blaze
我是 meteor 的新手,在 blaze 中使用 #each
很费力。
我尝试遵循 this answer on Whosebug,但我的要求略有不同。
我有一个 json 对象数组:
{
"accounting": [{
"firstName": "John",
"lastName": "Doe",
"age": 23
},
{
"firstName": "Mary",
"lastName": "Smith",
"age": 32
},
{
"firstName": "Mike",
"lastName": "Nolan",
"age": 21
}
]
}
如何在 meteor 项目中使用 blaze(特别是使用 #each 迭代数组)显示每个对象的 firstName。
我尝试了很多不同的方法,使用了多种辅助方法,但无法实现。如果有人可以帮助。
此外,如果不可能,请告诉替代方案以实现相同的效果。
数据来自 API 调用,数据格式是 json 对象,但存储为 Session 变量(因此我将从中获取数据辅助方法,使用 Session.get()
).
这将取决于您的数据来自何处。在我的示例中,您可以将我的硬编码变量替换为您的对象的源代码。如果你添加它来自哪里我可以修改我的解决方案。
基本上,您只需 return 带有辅助函数的 JSON 对象内部的对象数组。从那里您可以在 #each
块中调用助手,并直接使用 {{firstName}}
引用 firstName
模板
<template name="yourTemplateName">
{{#each accounting}}
{{firstName}}
{{/each}}
</template>
帮手
Template.yourTemplateName.helpers({
accounting: function () {
var data = Session.get('apiResponse');
//You return the array of objects, which can then be iterated with each
if (!_.isEmpty(data)){
return data.accounting;
} else {
return []
}
}
});
我假设 API 响应位于名为 apiResponse 的会话变量中。
定义一个helper如下:
Template.body.helpers({
response: function () {
return Session.get('apiResponse');
}
});
在您的模板中,使用 #with
模板标签调用响应助手以设置数据上下文,并在此标签内使用 #each
模板标签迭代会计数组。
<body>
{{#with response}}
{{#each accounting}}
<p>{{firstName}} {{lastName}} is {{age}} years old.</p>
{{/each}}
{{/with}}
</body>
您将在浏览器中看到此内容 window -
John Doe is 23 years old.
Mary Smith is 32 years old.
Mike Nolan is 21 years old.
我是 meteor 的新手,在 blaze 中使用 #each
很费力。
我尝试遵循 this answer on Whosebug,但我的要求略有不同。
我有一个 json 对象数组:
{
"accounting": [{
"firstName": "John",
"lastName": "Doe",
"age": 23
},
{
"firstName": "Mary",
"lastName": "Smith",
"age": 32
},
{
"firstName": "Mike",
"lastName": "Nolan",
"age": 21
}
]
}
如何在 meteor 项目中使用 blaze(特别是使用 #each 迭代数组)显示每个对象的 firstName。
我尝试了很多不同的方法,使用了多种辅助方法,但无法实现。如果有人可以帮助。
此外,如果不可能,请告诉替代方案以实现相同的效果。
数据来自 API 调用,数据格式是 json 对象,但存储为 Session 变量(因此我将从中获取数据辅助方法,使用 Session.get()
).
这将取决于您的数据来自何处。在我的示例中,您可以将我的硬编码变量替换为您的对象的源代码。如果你添加它来自哪里我可以修改我的解决方案。
基本上,您只需 return 带有辅助函数的 JSON 对象内部的对象数组。从那里您可以在 #each
块中调用助手,并直接使用 {{firstName}}
firstName
模板
<template name="yourTemplateName">
{{#each accounting}}
{{firstName}}
{{/each}}
</template>
帮手
Template.yourTemplateName.helpers({
accounting: function () {
var data = Session.get('apiResponse');
//You return the array of objects, which can then be iterated with each
if (!_.isEmpty(data)){
return data.accounting;
} else {
return []
}
}
});
我假设 API 响应位于名为 apiResponse 的会话变量中。
定义一个helper如下:
Template.body.helpers({
response: function () {
return Session.get('apiResponse');
}
});
在您的模板中,使用 #with
模板标签调用响应助手以设置数据上下文,并在此标签内使用 #each
模板标签迭代会计数组。
<body>
{{#with response}}
{{#each accounting}}
<p>{{firstName}} {{lastName}} is {{age}} years old.</p>
{{/each}}
{{/with}}
</body>
您将在浏览器中看到此内容 window -
John Doe is 23 years old.
Mary Smith is 32 years old.
Mike Nolan is 21 years old.