javascript - 无法创建 Handlebars 模板

标签 javascript backbone.js handlebars.js require-handlebars

我有一个 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/

相关文章:

javascript - jQuery 从 name[] 获取选中的复选框

javascript - 选择非 "spanned"的文本

javascript - 如何在 Parse.com CloudCode 上创建自定义帮助器模块以与 then() Promise 一起使用?类型错误 : Cannot call method 'then' of undefined

javascript - 主干事件处理程序不起作用

ember.js - Ember : accessing {{render}} options hash in controller

javascript - 等效于 ES6 Promises 的 BlueBird Promise.props?

javascript - 使用 Backbone.js 显示 Div

backbone.js - 在新窗口中打开主干 View

javascript - 如何调试 Mustache js 模板?

javascript - Handlebars - #if 基于 #each 中的父属性