[英]Iterating over array of objects in Handlebars
我實際上是在JSON對象中執行此操作,但是對於這個問題,我將進行簡化。 我似乎無法正確構建我的Handlebars模板。 這是我要傳遞的對象的示例數組:
var data = {
DocumentInfo: [
{
Category: "General",
DocumentList: [
{
DocumentName: "Document Name 1 - General",
DocumentLocation: "Document Location 1 - General"
},
{
DocumentName: "Document Name 2 - General",
DocumentLocation: "Document Location 2 - General"
}
]
},
{
Category: "Unit Documents",
DocumentList: [
{
DocumentName: "Document Name 1 - Unit Documents",
DocumentList: "Document Location 1 - Unit Documents"
}
]
},
{
Category: "Minutes"
}
]
};
這是Handlebars模板和Div的運行方向:
<div id="DocumentResults"></div>
<script id="document-template" type="text/x-handlebars-template">
<div>
{{#if DocumentInfo}}
{{#DocumentInfo}}
{{#Category}}
<div class="row">
<div class="col-md-12">
<h2>{{this}}</h2>
{{#DocumentList}}
<p>{{DocumentName}} at {{DocumentLocation}}</p>
{{/DocumentList}}
</div>
</div>
{{/Category}}
{{/DocumentInfo}}
{{else}}
<p>There are no documents available at this time</p>
{{/if}}
</div>
</script>
最后,這是構建Handlebars輸出的JavaScript:
var source = $.trim($("#document-template").html());
var template = Handlebars.compile(source);
var $docData = $(template(data));
$("#DocumentResults").empty().append($docData);
問題是,唯一生成的是標頭字段。 為什么不為每個類別遍歷我的其他數組(DocumentList)? 而且,我可以獲取標題值的唯一方法是使用{{this}}。 如果我將其替換為{{Category}},則不會顯示任何內容。 我看不到我在這里做錯了什么。
檢查此jsfiddle: http : //jsfiddle.net/KPCh4/
var source = $("#document-template").html();
var template = Handlebars.compile(source);
var html = template(data);
$('#DocumentResults').html(html);
我仍然專注於{{#each}}進行迭代; #
實際上是一個快捷方式。 不要混淆{{Category}}
和{{#Category}}
。 前者輸出屬性的值;前者輸出屬性的值。 后者是一個列表(請參閱#
)。
我讓您對代碼段進行了細化:)
希望這可以幫助,
R.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.