Handlebars js不遍历对象

Handlebars js not iterating over object

我正在使用 node.js 构建一个应用程序,并在服务器和客户端模板中使用 handlebars。但是,我在遍历对象时遇到问题。这是我的代码:

我的 .js 文件:

$(function () {
  var theTemplateScript = $("#update_address_distributor_template").html();
  context.city = 'london';
  var theTemplate = Handlebars.compile(theTemplateScript);
  var theCompiledHtml = theTemplate(context);
  $('.update_address_distributor_template_placeholder').html(theCompiledHtml);
});

我的 html 文件:

<script id="update_address_distributor_template" type="text/x-handlebars-template">
   <form class="form-horizontal" role="form" id="update_distributor_form">
      \{{city}} //correctly prints out london
      \{{address_distributors.length}} //returns 2, so i know the object exists
      {{#each address_distributors}}
       \{{name}} //does not print anything
      {{/each}}
    </form>
</script>

我的上下文对象:

{
    address_distributors: {
        [

            {
                name: 'nike',
                id: '1'
            },

            {
                name: 'yokohama',
                id: '4'
            }

        ]
    },

    city: 'london'

}

我的 {{#each ../address_distributors}} ... {{/each}} 没有打印任何东西。我知道我的 addres_distributors 对象退出了,因为 \{{address_distributors.length}} 在 html 页面上打印了 2。此外,为了测试我的车把模板是否设置正确,我设置了 context.city = 'london'; 以查看它是否会打印出来,它确实打印出来了。所以我知道这个问题与对象有关...

有人可以帮忙吗?

提前致谢!

name 变量不存在。尝试

{{this.name}}

此外,您可以简单地尝试

  {{#each address_distributors}}
    Anything // Just to see if your loop works.
  {{/each}}

你的数据有问题,我试过下面的数据:

{ "address_distributors": [ { name: 'nike', id: '1' }, { name: 'yokohama', id: '4' } ], city: 'london' }

我得到以下结果:

london //correctly prints out london
2 //returns 2, so i know the object exists
nike //does not print anything
yokohama //does not print anything

这是我的 fiddle 测试:https://jsfiddle.net/ChristopheThiry/30xh7epu/