一尘不染

无法使用Ember JS的Handlebars JS遍历嵌套的JSON数组(大写属性)

json

我正在学习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]

我不确定这是否是问题。


阅读 238

收藏
2020-07-27

共1个答案

一尘不染

大写变量被认为是全局范围,您需要完全限定它们或使其变为小写

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>
2020-07-27