I would like to keep all my template markup files in an external html file while using jQuery
ajax to communicate with the server using PHP
. PHP will return only variable data in a json
object.
Q: How can I organize this so that using the code below my html template is in an external file?
jquery:
$.ajax({ type: "POST", async: false, url: "ajaxHandler.php",// normally the template, but i need php for dB connect dataType: "json", success: function(data){ var aaa = data.aaa, bbb = data.bbb, ccc = data.ccc; console.log(aaa+' '+bbb+' '+ccc); } });
php:
$aaa = 1;
$bbb = 'bbb';
$ccc = "$aaa $bbb";
echo json_encode(array( "aaa"=>$aaa, "bbb"=>$bbb, "ccc"=>$ccc ));
my index.html contains:
<table class="entries"> <script id="template" type="text/x-handlebars-template"> <tr> <td>{{aaa}}</td> <td>{{bbb}}</td> <td>{{ccc}}</td> </tr> </script> </table>
but i would like to keep this in an external file
You'll either need to precompile your templates or load and compile the .hbs
files with Ajax when requested. After that you can just get the template from Handlebars.templates
, populate it with your data and append it to your entries
yourtemplate.hbs
<tr>
<td>{{aaa}}</td>
<td>{{bbb}}</td>
<td>{{ccc}}</td>
</tr>
JavaScript
$.ajax({ type: "POST",
async: true,
url: "ajaxHandler.php",
dataType: "json",
success: function(data){
var template = Handlebars.template["yourtemplate.hbs"],
html = template(data);
$(".entries").append(html);
}
});