Handlebars未呈现JSON上下文数据,正在获取空模板

Handlebars not rendering JSON context data, getting empty template

本文关键字:获取 数据 JSON 上下文 Handlebars      更新时间:2023-09-26

我遇到了一个奇怪的问题,Handlebars正确编译了我的模板,但在传递上下文数据时,html中的结果字段为空。我已经确认我的JSON数据实际上是一个javascript对象,而不是字符串。如果其他地方对此有回应,我深表歉意。我看到了很多关于JSON字符串需要成为实际对象的答案,但正如我所说,事实并非如此。

模板:

<script type="text/x-handlebars-template" id="items-template">
{{#each downloads}}
<div class="download-item">
    <h3>{{pagetitle}}</h3>
    <p>{{description}}</p>
</div>
{{/each}}
</script>

JS:

var source = $("#items-template").html();
var template = Handlebars.compile( $.trim(source) );
var html = template({
    downloads:[
        {pagetitle:'title', description:'the description'},
        {pagetitle:'title', description:'the description'},
        {pagetitle:'title', description:'the description'}
    ]
});

html(只有一个空白项)的结果:

<div class="download-item">
    <h3></h3>
    <p></p>
</div>

如有任何见解,我们将不胜感激。如果我在别人看到之前就弄清楚了,我一定会发布最新消息。

您应该使用this

{{#each downloads}}
<div class="download-item">
    <h3>{{this.pagetitle}}</h3>
    <p>{{this.description}}</p>
</div>
{{/each}}