[英]Iterate over a json object array in blaze
我是新來的流星,並且一直在努力使用#each
。 我嘗試在stackoverflow上遵循此答案 ,但我的要求略有不同。
我有一個json對象數組:
{
"accounting": [{
"firstName": "John",
"lastName": "Doe",
"age": 23
},
{
"firstName": "Mary",
"lastName": "Smith",
"age": 32
},
{
"firstName": "Mike",
"lastName": "Nolan",
"age": 21
}
]
}
如何在流星項目中使用blaze(特別是使用#each迭代數組)顯示每個對象的firstName。
我嘗試了多種不同的方法,使用了多種輔助方法,但無法實現。 如果有人可以幫忙。
另外,如果不可能,請告訴替代方案以達到相同目的。
數據來自API調用,數據格式為json對象,但存儲為Session變量(因此,我將使用Session.get()
在helper方法中從中獲取數據)。
這將取決於您的數據來自何處。 在我的示例中,您可以將我的硬編碼變量替換為對象的源。 如果您添加它的來源,我可以修改我的解決方案。
基本上,您只需要使用輔助函數返回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的會話變量中。
定義一個助手,如下所示:
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>
您將在瀏覽器窗口中看到此內容-
John Doe is 23 years old.
Mary Smith is 32 years old.
Mike Nolan is 21 years old.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.