我在Handlebars中创建了一个帮助逻辑的帮助器,但我的模板将返回的html解析为文本而不是html.
我有一个测验结果页面,在测验完成后呈现:
<script id="quiz-result" type="text/x-handlebars-template">
{{#each rounds}}
{{round_end_result}}
{{/each}}
<div class="clear"></div>
</script>
Run Code Online (Sandbox Code Playgroud)
对于每一轮,我使用一个帮助器来确定渲染圆形结果的模板:
Handlebars.registerHelper("round_end_result", function() {
if (this.correct) {
var source = '';
if (this.guess == this.correct) {
console.log("correct guess");
var source = $("#round-end-correct").html();
} else {
var source = $("#round-end-wrong").html();
}
var template = Handlebars.compile(source);
var context = this;
var html = template(context);
console.log(html);
return html;
} else {
console.log("tie");
}
});
Run Code Online (Sandbox Code Playgroud)
这是一个描述正确回合的模板(让我们假设它呈现了#round-end-correct模板):
<script id="round-end-correct" type="text/x-handlebars-template">
<div></div>
</script>
Run Code Online (Sandbox Code Playgroud)
以下是渲染的内容:
<div></div>
Run Code Online (Sandbox Code Playgroud)
不是HTML,而是文本.我如何让它实际将HTML呈现为HTML而不是文本?
我使用Handlebars.js作为我的Backbone.js应用程序的模板工具.我的视图中的渲染功能通常如下所示:
var source = $("#round").html();
var template = Handlebars.compile(source);
var context = JSON.parse(JSON.stringify(this.model));
var html = template(context);
$(this.el).html(html);
return this;
Run Code Online (Sandbox Code Playgroud)
以上代码通过以下代码附加到主应用程序视图(这是调用上述代码的代码):
$('div#round-container', this.el).append(roundView.render().el);
Run Code Online (Sandbox Code Playgroud)
我的Handlebars模板处理所有样式和布局,因此我将视图的"el"元素留空.Backbone.js会自动在Handlebars模板周围添加周围的div标签.我认为这是因为"el"元素是空白的.有没有办法防止添加周围的div标签?谢谢!
Handlebars无法读取我将其作为上下文发送的JSON对象.
这是调用Mustache模板并为其提供上下文的函数:
render: function() {
var source = $("#round").html();
var template = Handlebars.compile(source);
var context = JSON.stringify(this.model);
console.log(context);
var html = template(context);
$(this.el).html(html);
return this;
},
Run Code Online (Sandbox Code Playgroud)
这是我传递的JSON对象:
{"result":0,"friend1":{"firstName":"Ape","lastName":"Head","fbID":329018,"kScore":99,"profilePic":""},"friend2":{"firstName":"Ape","lastName":"Hands","fbID":32,"kScore":70,"profilePic":""}}
Run Code Online (Sandbox Code Playgroud)
这是Handlebars模板:
<script id="round" type="text/x-handlebars-template">
{{#with friend1}}
<h2>{{firstName}} {{lastName}}</h2>
{{/with}}
</script>
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
Uncaught TypeError: Cannot read property 'firstName' of undefined
Run Code Online (Sandbox Code Playgroud)