首页 > 解决方案 > Handlebars #each 块不起作用 - “this”范围仍然是全局范围

问题描述

我遇到了#each 块没有循环任何内容的问题。

我认为这是我的应用程序的问题,所以我尝试在 CopePen 中重新创建错误,但遇到了同样的问题。

这是笔:https ://codepen.io/hrsetyono/pen/YzZoRgg?editors=1111

这是一个非常简单的 HTML 示例:

<main></main>

<div id="template-list" style="display:none;">
  <h1>{{ title }}</h1>
  <table>
    <thead>
      <th>Name</th>
      <th>Job</th>
    </thead>
    <tbody>
    {{#each people }}
      <tr>
        <td>
          <strong>{{ name }}</strong>
        </td>
        <td>
          {{ job }}
        </td>
      </tr>
    {{/each }}
    </tbody>
  </table>
</div>

然后是JS:

let data = {
  title: 'Employee List',
  people: [
    { name: 'John', job: 'Gardener' },
    { name: 'Sarah', job: 'Sales' }
  ]
};

let rawTemplate = document.querySelector( '#template-list' ).innerHTML;
let $target = document.querySelector( 'main' );

let template = Handlebars.compile( rawTemplate );
let html = template( data );
$target.innerHTML = html; 

结果是空表,因为 #each 循环没有正确设置范围。

标签: javascripthandlebars.js

解决方案


显然 Handlebars 模板必须<script>像这样在里面:

<script id="template" type="text/x-handlebars-template">
  ...
</script>

现在一切正常


推荐阅读