[英]Handlebars Helper Function
我正在嘗試從把手中的輔助函數返回一個值並顯示它,這是我的代碼-
<div id="test"></div>
<script id="template" type="text/x-handlebars-template">
{{#each this}}
<hr/>
<div id="table">
<table>
<tr>
<td>
<div id="steps" style="color: #000000; font-size:36px;">{{steps}}</div><br></td>
</td>
</tr>
</table>
</div>
{{/each}}
</script>
<script
src="http://cdnjs.cloudflare.com/ajax/libs/mustache.js/0.7.0/mustache.min.js"></script>
<script type="text/javascript"
src="//ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.js"></script>
<script>
$(document)
.ready(
function() {
var source = $("#template").html();
var template = Handlebars.compile(source);
var rdata = [ {
"totalSteps" : 100,
"name" : "Dummy",
"heightFeet" : 5,
"averageSteps" : 10,
}, {
"totalSteps" : 10000,
"name" : "TestMan",
"heightFeet" : 4,
"averageSteps" : 10,
} ];
Handlebars.registerHelper('steps', function(rdata,index) {
var val=rdata[index].totalSteps;
return val.toLocaleString();
});
var ht = template(rdata);
$("#test").html(ht);
});
</script>
但是,我得到這個錯誤
Uncaught TypeError: Cannot read property 'totalSteps' of undefined
另外,我試圖寫這樣的功能-
$("#class").each function(index) {
return rdata[index].totalSteps;
});
但它不會顯示任何內容。 誰能幫我解決這個問題。
您需要將所需的數據傳遞給助手。 這是一個簡化的版本。
{{#each rdata as |value index|}}
{{steps ../rdata index}}
{{/each}}
{
rdata: [ {
totalSteps: 100,
name: "Dummy",
heightFeet: 5,
averageSteps : 10,
}, {
totalSteps : 10000,
name: "TestMan",
heightFeet: 4,
averageSteps: 10,
}]
}
Handlebars.registerHelper('steps', function(rdata,index) {
var val=rdata[index].totalSteps;
return val.toLocaleString();
});
上面的示例在tryhandlebarsjs中起作用
我只是這樣做
Handlebars.registerHelper('steps', function() {
return this.totalSteps;
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.