我需要创建一个包含HandleBars和json的表。我的建议是这样的:
<script type="text/x-handlebars">
{{NGRID 'json'}}
</script>
和NGRID
的注册助手是这样的:
Handlebars.registerHelper('NGRID',function(json){
// create elements <table> and a <tbody>
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
// cells creation
for (var j = 0; j <= 2; j++) {
// table row creation
var row = document.createElement("tr");
for (var i = 0; i < 2; i++) {
// create element <td> and text node
//Make text node the contents of <td> element
// put <td> at end of the table row
var cell = document.createElement("td");
var cellText = document.createTextNode("cell is row "+j+", column "+i);
cell.appendChild(cellText);
row.appendChild(cell);
}
//row added to end of table body
tblBody.appendChild(row);
}
// append the <tbody> inside the <table>
tbl.appendChild(tblBody);
// put <table> in the <body>
// tbl border attribute to
tbl.setAttribute("border", "2");
return tbl;
});
但是在我的html文件中,结果是这样的:
[object HTMLTableElement]
但我想看表。
答案 0 :(得分:3)
句柄使用返回对象中的toString
,因为您收到[object HTMLTableElement]
。
此外,把手逃脱返回的字符串,以防止XSS攻击。您需要在您信任的内容中使用Handlebars.SafeString
来保护您的html。
为简单起见,我返回new Handlebars.SafeString(tbl.outerHTML)
并继续工作。