[英]Handlebars template not displaying context data
我正在嘗試使用Node express和Handlebars作為模板引擎來構建測驗應用程序。
我有以下模板:
<div id="quiz">
<div class="container">
<div class="row" id="quiz-header-row">
<div>
<div id="question-title"></div>
</div>
</div>
<div class="row" id="quiz-choices-row">
<div id="choices"></div>
</div>
<div class="row" id="quiz-footer-row">
<button id="quiz-next-btn" class="btn btn-success">Next</button>
</div>
</div>
</div>
<!-- Template -->
<script id="choices-template" type="text/x-handlebars-template">
<div>\{{choices}}</div>
<div>
{{#each choices}}
<a href="#"">{{this}}</a>
{{/each}}
</div>
</script>
如果在花括號前不使用反斜杠,則把手將顯示一個空字符串,因此無法編寫以下代碼:
<div>{{choices}}</div>
在我必須使用的車把官方網站上找到: \\ {{choices}} 。
用數據填充模板的javascript:
renderChoices: function() {
var template = Handlebars.compile($('#choices-template').html());
var context = {
// array of quiz item choices
choices: Quiz.questions[Quiz.currentIndex].choices
};
$('#choices').html(template(context));
},
我面臨的問題是#each塊不顯示任何內容。 由於服務器拋出“服務器內部錯誤:500”,因此無法像上面的示例中那樣使用{{#each choices}}之前的反斜杠。
這是控制台記錄的上下文: 控制台日志
下面的小提琴可以根據需要工作,不需要反斜杠
擺弄 。
但是,我在使用Node的項目中運行的完全相同的代碼不會顯示在#each塊內編寫的任何內容。
我在服務器(express-handlebars)和客戶端上都有把手。 考慮到結果,我做錯了事情。
先感謝您。
編輯:通過預編譯外部文件中的模板並將其作為腳本包含在視圖中來修復。
嘗試這樣的事情:
{{#each choices as |choice|}}
<a href="#">{{choice}}</a>
{{/each}}
並確保choices
符合您的期望。
我只是試圖執行您的代碼,它正在打印數據,我使用了jquery-2.2.1和handlebars 2.0.0
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<script id="address-template" type="text/x-handlebars-template">
<div>
{{#each choices}}
<a href="#"">{{this}}</a>
{{/each}}
</div>
</script>
<!--Your new content will be displayed in here-->
<div class="content-placeholder"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.js">
</script>
<script>
$(function () {
// Grab the template script
var theTemplateScript = $("#address-template").html();
// Compile the template
var theTemplate = Handlebars.compile(theTemplateScript);
// Define our data object
var context={
choices: ["choice1","choice2","choice3"]
};
// Pass our data to the template
var theCompiledHtml = theTemplate(context);
// Add the compiled html to the page
$('.content-placeholder').html(theCompiledHtml);
});
</script>
</body>
</html>
這是通向punker的鏈接 ,我也嘗試使用把手4.0.3和jquery 3.1.1,它運行良好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.