I'm new to using templates and I have a question about reusing them. On load, I get the template and data:
$(function() {
var source, content;
$.get('/templates/template.html', function(data) {
source = data;
})
$.getJSON("/data/data.php", function(data) {
content = data;
})
$(document).ajaxStop(function() {
window.template = Handlebars.compile(source);
$('#user-list tbody').html(window.template(content));
})
})
The template is as follows:
{{#users}}
<tr>
<td> {{name}} </td>
</tr>
{{/users}}
Here's the HTML in the same file:
<div id="content-div">
<table id="user-list">
<thead></thead>
<tbody></tbody>
</table>
</div>
How would I reuse this template when I want to append a row? For example:
function loadMore() {
$.ajax({
type : 'POST',
url : '/data/more.php',
dataType : 'json',
success : function(data) {
$('#user-list tbody').append(window.template(data));
}
});
}
It gets the data but won't append to the tbody
. Why is this?
Update: Also, is it possible to put the entire table structure in the template file as such?
<table id="user-list">
<thead></thead>
<tbody>
{{#users}}
<tr>
<td> {{name}} </td>
</tr>
{{/users}}
</tbody>
</table>
Only on the initial page load would it pull in the entire structure but when I want to append additional rows, it would just append the <tr>
portion.
Update: Maybe an off-topic side question but is this generally the correct way to approach this situation? I envision a folder full of templates that I can just pull in and use them when I need them. Is it correct to grab them via an ajax call?