我有一个 Handlebars 模板,它采用 JSON 对象。
处理条形码 -
<script id="list" type="x-handlebars-template">
{{#each items}} {{! Each item is an "li" }}
<li>
{{label}} :
{{value}}
{{#if items}}
<ul>
{{> list}} {{! Recursively render the partial }}
</ul>
{{/if}}
</li>
{{/each}}
<script id="main" type="x-handlebars-template">
<ul>
{{> list}}
</ul>
</script>
JSON 对象为 -
var items =[
{ "label": "TotalRented", "value": "5" },
{ "label": "AncilleryItems", "items": [
{ "label": "Item", "value": "CarSeat" },
{ "label": "Qty", "value": "2" },
{ "label": "Cost","items": [
{ "label": "VAT", "value": "$20" },
{ "label": "Total", "value": "$100" }
]
},
{ "label": "Item", "value": "GPS" },
{ "label": "Qty", "value": "1" },
{ "label": "Cost", "items": [
{ "label": "VAT", "value": "$10" },
{ "label": "Total", "value": "$50" }
]
}
]
},
{ "label": "Colour", "value": "red" }
];
// The main template.
var main = Handlebars.compile( $( "#main" ).html() );
// Register the list partial that "main" uses.
Handlebars.registerPartial( "list", $( "#list" ).html() );
// Render the list.
$( "body" ).html( main( { items: items } ) );
此代码将为我正确呈现树结构数据,如 fiddle - http://jsfiddle.net/achyut/V6HNd/1/ 所示。
现在我的 JSON 对象已更改,它现在有额外的方括号,用于逻辑分隔。我现在无法使用额外的括号渲染树结构。谁能告诉我 Handlebars 模板中需要更改哪些代码。
新的 JSON 对象是
var items = [
{ "label": "TotalRented", "value": "5" },
{ "label": "AncilleryItems", "items": [
[
{ "label": "Item", "value": "CarSeat" },
{ "label": "Qty", "value": "2" },
{ "label": "Cost","items": [
[
{ "label": "VAT", "value": "$20" },
{ "label": "Total", "value": "$100" }
]
]
}
],
[
{ "label": "Item", "value": "GPS" },
{ "label": "Qty", "value": "1" },
{ "label": "Cost", "items": [
[
{ "label": "VAT", "value": "$10" },
{ "label": "Total", "value": "$50" }
]
]
}
]
]
},
{ "label": "Colour", "value": "red" }
]
最佳答案
由于您有项目数组,因此必须再次循环并访问可以使用 this
的对象
{{#each items}}
{{#each this}} {{! Each item is an "li" }}
{{! Code here }}
{{/each}}
{{/each}}
关于javascript - 无法创建 Handlebars 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23680818/