【问题标题】:Handlebars js not iterating over objectHandlebars js没有迭代对象
【发布时间】:2016-03-29 19:37:45
【问题描述】:

我正在使用 node.js 构建一个应用程序,并且正在使用把手用于服务器和客户端模板。但是,我在迭代对象时遇到了麻烦。这是我的代码:

我的 .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'; 以查看它是否会打印出来,它确实如此。所以我知道这个问题与对象有关...

有人可以帮忙吗?

提前致谢!

【问题讨论】:

  • ../ 是不是有点奇怪?
  • 我把它拿出来了;我还是不行。。
  • 名称在哪里/如何定义?

标签: javascript node.js handlebars.js


【解决方案1】:

你的数据有问题,我用下面的数据试了一下:

{ "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

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

【讨论】:

    【解决方案2】:

    name 变量不存在。试试

    {{this.name}}
    

    你也可以试试

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

    【讨论】:

    • 嗨 - '任何东西'都不起作用。我用示例上下文对象更新了我的问题
    • 所以你的循环甚至不起作用。为什么你首先要有../
    猜你喜欢
    • 2014-10-18
    • 2013-10-01
    • 1970-01-01
    • 2014-05-06
    • 1970-01-01
    • 1970-01-01
    • 2019-09-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多