javascript - "not well-formed"在从脚本将 json 加载到模板时由 handlebars.js 调用

标签 javascript json handlebars.js

我正在尝试使用 handlebars.js 创建 html,然后将 html 注入(inject)网页。在尝试集成服务器之前,我正在使用脚本内部编写的 json 对其进行测试。我已经在验证器中检查了 json,一切都很好,但我仍然从 Handlebars 模板中收到一个错误,声称“格式不正确”。

我读到一些其他人遇到跨源请求问题,但我使用 Firefox,这是他们建议的解决方案(问:not well-formed Source File in mozilla firefox)

会不会是我的 handlebars 文件有问题?

这是我的js代码:

var html;
    var data= { "array":[
        {"firstname":"Joe","lastname":"Shmoe"},
        {"firstname":"John","lastname":"Connor"}
        ]};
    console.log(data);
    $.get("templates/coach-list-template.hbs",function(data){
        var template= Handlebars.compile(data);
        var handlebarshtml=template(data);
        console.log(handlebarshtml);
        console.log("Data: "+data);
    },"html"); 

这是 Handlebars 代码:

{{#each array}}
<div class="row">
    <div class="col-100"> {{firstname}} {{lastname}}</div>
</div>
{{/each}}

最佳答案

您需要编译模板,而不是数据。所以,如果你的 HTML 中有这个:

<script type="text/x-handlebars-template" id="mytemplate">
  {{#each array}}
  <div class="row">
    <div class="col-100"> {{firstname}} {{lastname}}</div>
  </div>
  {{/each}}
</script>

你编译那个模板

var template = Handlebars.compile(document.getElementById('mytemplate').innerHTML);

然后使用该模板应用数据:

var html = template(data);

关于javascript - "not well-formed"在从脚本将 json 加载到模板时由 handlebars.js 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27541915/

相关文章:

javascript - Handlebars helper 比较两个数组并返回差异

javascript - 如何使用我的 javascript 函数摆脱周末约会?

java - 为什么 Swagger 在示例中创建了一个 systemId 字段?

node.js - 如何通过 node.js 将文件包含到 .handlebar 文件

javascript - 在 Javascript 中使用正则表达式仅检索匹配字符串的一部分

java - Java 中 JSON 嵌套数据创建失败

javascript - 使用 handlebar js 使用 data() 将 json 值存储到 li

javascript - d3.js 在线聊天网格问题

javascript - 我的 JavaScript 随机数总是初始化为 1?

javascript - 在 HTTP DELETE 请求中传递多个参数