Reputation: 1578
I've been trying to iterate a JSON variable to create a table using jQuery template/tmpl to do so, I've succeeded on iterating one-dimensional JSON but when trying to generate the table's body where you need to generate a two-dimensional iteration cell >inside> row, I couldn't do it.
Any help is profusely appreciated!
My code:
//$("#blogPostTemplate").tmpl(blogPosts).appendTo("#blogPostContainer");
// Grab this template fill it with this data append it to this div
var data = [{
tableTitle: ["Stand With The Hammonds"],
thead: [{
header: 'H1'
}, {
header: 'H2'
}, {
header: 'H3'
}],
tbody: [
[{
col: 0
}, {
col: 1
}, {
col: 2
}],
[{
col: 0
}, {
col: 1
}, {
col: 2
}]
]
}];
$('#blogPostTemplate').tmpl(data).appendTo('#blogPostContainer');
table {
border: 1px solid #F00;
}
tbody,
tr,
td {
border: 1px solid #0F0;
}
thead,
th {
border: 1px solid #00F;
}
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<title>standwithrand</title>
</head>
<body>
<div id="blogPostContainer"></div>
<script id="blogPostTemplate" type="text/x-jQuery-tmpl">
<table>
<h1>${tableTitle}</h1>
<thead>
<tr>
{{each thead}}
<th>${header}</th>{{/each}}
</tr>
</thead>
<tbody>
{{each tbody}}
<tr>
<td>${col}</td>
</tr>
{{/each}}
</tbody>
</table>
</script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script>
</body>
</html>
Upvotes: 2
Views: 242
Reputation: 154
I guess the problem is that you have to iterate through each row to generate each cell, so you only need to get the row index to access to each one. You could use the next fragment to generate each row and each cell:
<tbody>
{{each(idx) tbody}}
<tr>
{{each tbody[idx]}}
<td>${col}</td>
{{/each}}
</tr>
{{/each}}
</tbody>
Cheers, Jorge
Upvotes: 1