javascript - 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 循环没有正确设置范围。
解决方案
显然 Handlebars 模板必须<script>
像这样在里面:
<script id="template" type="text/x-handlebars-template">
...
</script>
现在一切正常
推荐阅读
- class - 在类中创建的模块实例如何从此类(Python 3)继承?
- scala - 尝试将 Spark DF 写入 Hive 表时出现错误“对未解析对象的限定符调用无效”
- python - 添加和规范化在熊猫中重复键的行
- python - Python Word Vect numpy 数组,保存到 csv 时出现维度错误,预期 1D 或 2D 数组,改为 0D 数组
- php - 静态属性将如何在队列中工作?
- asp.net-core - 如何使用 Azure Active Directory 在 ASP.NET Core 应用程序中获取经过身份验证的用户的名称
- python - 以毫秒为单位将时间戳传递给由 SQLite3 支持的 SQLAlchemy
- javascript - JavaScript 函数在 Django 上不起作用
- python - 退出程序后输入数据不会立即保存
- android - 使用 RecyclerView 删除 Sqlite 中的行