2014-05-15 103 views
1

我有一個需要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 })); 

此代碼將呈現樹結構的數據正確,我作爲小提琴 - http://jsfiddle.net/achyut/V6HNd/1/

現在我的JSON對象已被更改,現在它有多餘的方括號,用於邏輯分離。我現在無法使用額外的括號渲染樹結構。任何人都可以告訴哪些代碼需要在車把模板中進行更改。

新的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" } 
] 
+0

所以'items'現'[[{...},...]]'而不是'[{...},...]'?爲什麼不預處理數據以使其再次變得明智?只需剝離'items'中的一層數組。 –

+0

是的你是對的。關於剝離,我實際上不能這樣做,因爲我實際上得到一個非常大的有效載荷,其中項目只是其中一個對象,我有一個非常大的車把模板呈現整個頁面。這只是我分享的一小塊。我無法爲這個小塊寫一個不同的邏輯 – Achyut

+0

@ muistooshort有沒有辦法單獨重寫手柄條代碼來渲染頁面 – Achyut

回答

0

既然你有一個項目數組,你必須循環就會再次訪問該對象可以使用this

{{#each items}} 
    {{#each this}} {{! Each item is an "li" }} 

    {{! Code here }} 

    {{/each}} 
{{/each}}