我是Handlebars和Javascript的新手,因此提前致歉。作为学习把手的一种方法,我正在尝试将在线示例中的所有基本组件放到一个独立的网页中。但是它运行不正常。
<html>
<head>
<script type="text/javascript" src="scripts/jquery-3.1.1.min.js" />
<script type="text/javascript" src="scripts/handlebars-v4.0.5.js" />
</head>
<body>
<div id="content-placeholder"></div>
<script id="some-template" type="text/x-handlebars-template">
<table>
<thead>
<th>Username</th>
<th>Real Name</th>
<th>Email</th>
</thead>
<tbody>
{{#users}}
<tr>
<td>{{username}}</td>
<td>{{firstName}} {{lastName}}</td>
<td>{{email}}</td>
</tr>
{{/users}}
</tbody>
</table>
</script>
<script>
var source = $("#some-template").html();
alert(source);
var template = Handlebars.compile(source);
var data = { users: [
{username: "alan", firstName: "Alan", lastName: "Johnson", email: "[email protected]" },
{username: "allison", firstName: "Allison", lastName: "House", email: "[email protected]" },
{username: "ryan", firstName: "Ryan", lastName: "Carson", email: "[email protected]" }
]};
$("#content-placeholder").html(template(data));
</script>
</body>
</html>
另外,我无法打印源(alert(源)显示“未定义”)。缺少什么吗?谢谢您的帮助!
最佳答案
似乎您尚未在包含script
和jQuery
的顶部关闭Handlebars
ta。
您应该关闭脚本标签:
<script type="text/javascript" src="scripts/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="scripts/handlebars-v4.0.5.js"></script>
这是完整的工作代码
var source = $("#some-template").html();
alert(source);
var template = Handlebars.compile(source);
var data = {
users: [{
username: "alan",
firstName: "Alan",
lastName: "Johnson",
email: "[email protected]"
}, {
username: "allison",
firstName: "Allison",
lastName: "House",
email: "[email protected]"
}, {
username: "ryan",
firstName: "Ryan",
lastName: "Carson",
email: "[email protected]"
}]
};
$("#content-placeholder").html(template(data));
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.6/handlebars.min.js"></script>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<div id="content-placeholder"></div>
<script id="some-template" type="text/x-handlebars-template">
<table>
<thead>
<th>Username</th>
<th>Real Name</th>
<th>Email</th>
</thead>
<tbody>
{{#users}}
<tr>
<td>{{username}}</td>
<td>{{firstName}} {{lastName}}</td>
<td>{{email}}</td>
</tr>
{{/users}}
</tbody>
</table>
</script>
关于javascript - Handlebars :无法编译?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41622936/