【问题标题】:Handlebars not rendering JSON context data, getting empty template车把不呈现 JSON 上下文数据,获取空模板
【发布时间】:2013-08-07 15:41:53
【问题描述】:

我遇到了一个奇怪的问题,即 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>

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

【问题讨论】:

    标签: javascript handlebars.js


    【解决方案1】:

    你应该使用this

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

    【讨论】:

    • 我觉得有点愚蠢,但我刚刚发现了我的问题。我正在尝试添加这些车把作为旧网站页面翻新的一部分。它使用 modx evolution CMS。我不能在 dom 的脚本标签中使用把手模板,cms 在把手甚至有机会处理它们之前解析出 {{}}。我的解决方案是在 CMS 范围之外从外部加载模板。我会将您的答案标记为正确,因为无论如何我都应该使用this。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-20
    • 2021-09-29
    • 1970-01-01
    • 2020-01-16
    • 1970-01-01
    • 1970-01-01
    • 2013-06-08
    相关资源
    最近更新 更多