Asked By: Anonymous
I need to create a table with HandleBars and json. my proposal is some thing like this :
<script type="text/x-handlebars">
{{NGRID 'json'}}
</script>
and register helper for NGRID
is something like this :
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;
});
but in my html file the result is something like this :
[object HTMLTableElement]
but i want to see table.
Solution
Answered By: Anonymous
Handlebars use the toString
from the returned object, because this you receive [object HTMLTableElement]
.
Also, handlebars escape the returned string, to prevent XSS attack. You need to use Handlebars.SafeString
to your html don’t be escaped, in the content that you trust.
For simplicity I return new Handlebars.SafeString(tbl.outerHTML)
and work.