我在使用Handlerbars.js
的每个块助手时遇到了麻烦<html>
<head>
<script>
</script>
<script id="entry-template" type="text/x-handlebars-template">
<div class="entry">
{{#each people}}
<p>{{firstName}} {{lastName}}</p>
{{/each}}
</div>
</script>
<script src="lib/jquery-1.8.2.min.js"></script>
<script src="lib/handlebars.js"></script>
<script type='text/javascript'>
$(document).ready(function(){
var people = [
{firstName: "Yehuda", lastName: "Katz"},
{firstName: "Carl", lastName: "Lerche"},
{firstName: "Alan", lastName: "Johnson"}
]
var source = $("#entry-template").html();
var template = Handlebars.compile(source);
var html = template(people);
$('#content').html(html);
});
</script>
</head>
<body>
<div id="content">
</div>
</body>
</html>
如果我将模板更改为下面的代码,一切顺利:
<script id="entry-template" type="text/x-handlebars-template">
<div class="entry">
{{#.}}
<p>{{firstName}} {{lastName}}</p>
{{/.}}
</div>
</script>
如何使用每个帮助程序块?
答案 0 :(得分:0)
您可以.
使用this
或{{#each}}
:
<script id="entry-template" type="text/x-handlebars-template">
<div class="entry">
{{#each .}}
<p>{{firstName}} {{lastName}}</p>
{{/each}}
</div>
</script>
或:
<script id="entry-template" type="text/x-handlebars-template">
<div class="entry">
{{#each this}}
<p>{{firstName}} {{lastName}}</p>
{{/each}}
</div>
</script>
演示:
.
:http://jsfiddle.net/ambiguous/2Y4cF/ this
:http://jsfiddle.net/ambiguous/8Pe2Z/(感谢Ben提醒您这个提醒) {{#each people}}
的问题在于模板不知道您为JavaScript对象使用了什么名称。如果您想使用{{#each people}}
,则必须添加其他图层:
var html = template({ people: people });