javascript - Handlebars js不遍历对象

标签 javascript node.js handlebars.js

我正在使用 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。此外,为了测试我的 Handlebars 模板是否正确设置,我设置了 context.city = 'london'; 以查看它是否会打印出来,确实如此。所以我知道这个问题与对象有关...

有人可以帮忙吗?

提前致谢!

最佳答案

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

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

关于javascript - Handlebars js不遍历对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36226177/

相关文章:

javascript - 从数据库加载 iframe

javascript - 你能在 Grunt 任务中将 Grunt 变量传递给 JavaScript 函数吗?

javascript - 访问 JSON 数组中的键名

javascript - 自动选择 React 的 HTML 元素类型

javascript - jQuery:使字符串中的字母闪烁

mysql - mySQL 之后无法从 JSON 获取值

node.js - 将 excel(.xlsx) 文件转换为 JSON

html - Handlebars 布局中的 CSS 不适用于车身

javascript - 如何访问和更改 keystone.js 登录页面?

javascript - 该函数是否应该在服务器上异步运行