我刚刚开始学习Handlebars.js,我使用了Handlebars.js网站(http://handlebarsjs.com/expressions.html)来帮助在此处写下以下代码:
var story = {
url: "www.nytimes.com/colonizemars.html",
text: "We finally colonized mars!"
};
Handlebars.registerHelper('link', function(object) {
return new Handlebars.SafeString(
"<a href='" + object.url + "'>" + object.text + "</a>"
);
});
var theTemplateScript = $("#header").html();
var theTemplate = Handlebars.compile (theTemplateScript);
var temp = theTemplate(story);
console.log(temp);
$(function() {
$(document.body).append (temp);
});
我不确定为什么运行时出现以下错误:
未捕获的TypeError:无法读取未定义的属性'url'
谢谢!
答案 0 :(得分:0)
尝试替换
registerHelper('link', function(object)
与
registerHelper('link', function(text, url)
来自文档:
Handlebars.registerHelper('link', function(text, url) {
text = Handlebars.Utils.escapeExpression(text);
url = Handlebars.Utils.escapeExpression(url);
var result = '<a href="' + url + '">' + text + '</a>';
return new Handlebars.SafeString(result);
});
答案 1 :(得分:0)
事实证明,Handlebars对数据或上下文的格式非常挑剔。我对故事对象进行了以下更改,并且它有效。
var data = {
story : {
url: "www.nytimes.com/colonizemars.html",
text: "We finally colonized mars!"
}
};
所以现在我的整个代码看起来像这样:
<script id="header" type="text/x-handlebars-template">
{{{link story}}}
</script>
<script type="text/javascript">
Handlebars.registerHelper('link', function(object) {
return new Handlebars.SafeString("<a href='" + object.url + "'>" + object.text + "</a>"
);
});
var data = {
story : {
url: "www.nytimes.com/colonizemars.html",
text: "We finally colonized mars!"
}
};
var theTemplateScript = $("#header").html();
var theTemplate = Handlebars.compile (theTemplateScript);
var temp = theTemplate(data);
console.log(temp);
$(function() {
$(document.body).append (temp);
});
</script>