无法使用带有Ember JS的Handlebars JS循环嵌套的JSON数组(大写属性)

时间:2014-01-16 14:41:33

标签: json ember.js nested handlebars.js

我正在学习Ember JS和Handlebars JS,所以我对此很陌生。

我在尝试循环嵌套JSON数组时遇到问题。我无法遍历下面JSON中的“页面”。

这是JSON:

{
    "Pages": [
      {
        "Id": 1,
        "Name": "Page 1",
        "Objects": [
          {
            "Width": 100,
            "Height": 200,
            "Type": "Shape"
          },
          {
            "Width": 150,
            "Height": 250,
            "Type": "Image"     
          }
        ]
      },
      {
        "Id": 2,
        "Name": "Page 2",
        "Objects": [

        ]
      }
    ],
    "Settings": {
        "URL": "http://THEURL",
        "Location": true,
        "Navigation": true
     },
     "Id": 1,
     "Title": "The Title",
     "Description": "The Description"
}

这是我的车把模板:

<script type="text/x-handlebars" id="pages">
<div class="container">
    <div class="row">
        <h1>{{Title}}</h1> <!-- This works -->
        <h2>{{Description}}</h2> <!-- This works -->

        <!-- This doesn't work: -->
        <ul>
        {{#each Pages}}
              <li>Page ID: {{Id}} <br /> Page Name: {{Name}} <br />
                  <ul>
                  {{#each Objects}}
                    <li>{{Type}}</li>
                  {{/each}}
                  </ul>
              </li>
        {{/each}}
        </ul>

    </div>
</div>
</script>

另外,当我刚添加:

{{Pages}}
在把手模板中

,浏览器中的输出是:

[object Object],[object Object]

我不确定这是不是问题。

1 个答案:

答案 0 :(得分:7)

大写变量被视为全局范围,您需要完全限定它们或将它们设为小写

http://emberjs.jsbin.com/UhIGevUf/1/edit

<div class="container">
    <div class="row">
        <h1>{{model.Title}}</h1> <!-- This works -->
        <h2>{{model.Description}}</h2> <!-- This works -->

        <!-- This doesn't work: -->
        <ul>
        {{#each page in model.Pages}}
              <li>Page ID: {{page.Id}} <br /> Page Name: {{page.Name}} <br />
                  <ul>
                  {{#each obj in page.Objects}}
                    <li>{{obj.Type}}</li>
                  {{/each}}
                  </ul>
              </li>
        {{/each}}
        </ul>

    </div>
</div>