//HTML template
requirejs([
'handlebars',
'htmlTemplates/mydiv',
'text!htmlTemplates/mydiv.html'
],
function (notUsed0, mydivData, mydivTemplate)
{
console.log(mydivData);
var theTemplate = Handlebars.compile (mydivTemplate);
$(".mydiv").append(theTemplate(mydivData));
//error Uncaught TypeError: Cannot read property 'customerName' of undefined
}
);
数据 - mydiv.js
{
customerName: "peter"
}
模板 - mydiv.html
<div> Name: {{ customerName }} </div>
mydiv 是我的 index.html 的 body 标记内的 DIV 元素
-----编辑----- 我还尝试在函数内定义一个变量
var theData = {customerName:"Shop Page"};
现在一切正常,没有错误,但是 html 仍然没有附加到我的 index.html 中带有 mydiv id 的 DIV 中。为什么?
最佳答案
要将 myDiv.js
与 requirejs
一起使用,您必须将其内容包装在 Require 能够理解的声明中。查看文档 http://requirejs.org/docs/api.html#defsimple
将myDiv.js
的内容更改为:
define({
customerName: "peter"
});
关于javascript - 无法使用 require.js 读取 Handlebars 模板的数据对象文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18958276/